翻譯|使用教程|編輯:吉煒煒|2024-11-25 13:56:40.053|閱讀 98 次
概述:在本教程中,您將學習如何將 Maptiler 庫添加到使用 DHTMLX 構建的 JavaScript 調度程序的 Map 視圖。
# 界面/圖表報表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
DHTMLX Scheduler是一個全面的 UI 組件,用于處理面向業務的 Web 應用程序中復雜的調度和任務管理需求。但是,某些場景可能需要自定義解決方案。例如,如果項目的資源(即勞動力)有限,則需要確保以更高的精度分配他們的工作量。為此,應用條形圖等數據可視化工具會很有用。
地圖視圖是DHTMLX JavaScript Scheduler中用于顯示即將發生的事件的 10 個可自定義選項之一。默認情況下,它允許在地圖上顯示來自流行地圖提供商(例如 Google 地圖、OpenStreetMap 和 Mapbox)的計劃活動列表。如果這些默認選項不能滿足您的需求,最新的 Scheduler 版本可以為您的日歷添加自定義地圖適配器。在本教程中,您將學習如何將 Maptiler 庫添加到使用 DHTMLX 構建的 JavaScript 調度程序的 Map 視圖。
向調度程序添加自定義地圖適配器的分步指南
MapTiler是一款功能強大的地圖提供程序,可提供可自定義的高質量地圖圖塊,供開發者在各種項目(包括 Web 應用)中使用。在下面的示例中,您可以看到一個帶有地圖視圖的 JavaScript 調度程序,您可以在其中通過 MapTiler 查看地圖上的所有即將到來的約會。
	 
 
	
下面,讓我們詳細解釋如何向您的 Web 項目添加類似的功能。
步驟 1:初始化調度程序
您可以使用init方法初始化 DHTMLX Scheduler 。該方法將 HTML 容器(或其 ID)作為參數,Scheduler 將放置在其中。
scheduler.init("scheduler_here");
步驟 2:將地圖視圖添加到調度程序
由于地圖視圖不是 Scheduler 中的默認選項,因此您必須添加它。
步驟 3:創建自定義地圖適配器
現在,我們來集成自定義地圖適配器。為此,您需要創建一個實現 Scheduler 地圖適配器接口的類,該接口由我們文檔的此部分中描述的 9 種方法組成。
這些方法代表用戶可以使用 Scheduler 的地圖視圖執行的主要操作。
要創建 Maptiler 適配器,請使用以下代碼:
export class maptilerAdapter {
    constructor(scheduler) {
        this.map = null;
        this.options = {};
        this._markers = [];
        this.scheduler = scheduler;
    }
    initialize(container, options) {
        maptilersdk.config.apiKey = options.accessToken;
        const map = new maptilersdk.Map({
          container: container, // container's id or the HTML element in which the SDK will render the map
          style: maptilersdk.MapStyle.STREETS, // style of the map
          center:[options.initial_position.lng, options.initial_position.lat], // starting position [lng, lat]
          zoom: options.initial_zoom // starting zoom
        });
        }
}
MapTiler 的地圖使用maptilersdk.Map API 進行初始化,其中,您可以使用initialise()方法的第一個參數指定容器屬性。其他屬性可根據您的需要使用。
注意下面這行代碼:
maptilersdk.config.apikey = options.accesstoken;
這里,options.accesstoken指的是您的 MapTiler API 密鑰,它應該在scheduler.config.map_settings.accesstoken配置中設置。
步驟 4:在地圖上創建事件
您可以讓最終用戶通過雙擊在地圖上添加約會地點。您需要應用dblclick事件處理程序來實現此目標。在此事件處理程序中,您應該使用來自本機事件對象 ( e.lnglat.lat、e.lnglat.lng ) 的坐標創建一個調度程序事件。此外,您必須通過向指定的地理編碼發送請求來指定事件的位置。
以下是如何實現這一目標的一個例子:
map.on("dblclick",async function(e){
    let response = await fetch(`//api.maptiler.com/geocoding/${e.lngLat.lng},${e.lngLat.lat}.json?key=${options.accessToken}`).then(response => response.json());
    if (response.features){
        let address = response.features[0].place_name_en;
        scheduler.addEventNow({
            lat: e.lngLat.lat,
            lng: e.lngLat.lng,
            event_location: address,
            start_date: scheduler.getState().date,
            end_date: scheduler.date.add(scheduler.getState().date, scheduler.config.time_step, "minute")
        });
    } else {
        console.error("unable receive a position of the event");
    }
});
步驟 5:使用標記在地圖上顯示事件
現在,是時候向您展示使用特殊標記在日歷中顯示即將發生的事件的可能性了。在后臺,您可以使用多種方法來處理標記,例如addEventMarker(event)、removeEventMarker(eventId)、updateEventMarker(event)和clearEventMarkers()。
在我們的場景中,它的工作方式如下:
addEventMarker(event) {
    let config = [
        event.lng,
        event.lat
    ]
    if (!event.lat || !event.lng) {
        config = [this.options.error_position.lng, this.options.error_position.lat];
    }
    // create the popup
    const popup = new maptilersdk.Popup({ offset: 25 }).setHTML(this.scheduler.templates.map_info_content(event));
    // create the marker
    const marker = new maptilersdk.Marker()
        .setLngLat(config)
        .setPopup(popup)
        .addTo(this.map);
    // create the tooltip
    const tooltip = new maptilersdk.Popup({
            closeButton: false,
            closeOnClick: false
        });
    const markerInfo = {event, marker};
    // we need to collect all markers in order to find the required one when we will ipdate or delete it
    this._markers.push(markerInfo);
}
removeEventMarker(eventId) {
    for (let i = 0; i < this._markers.length; i++) {
        if (eventId == this._markers[i].event.id) {
            this._markers[i].marker.remove();
            this._markers.splice(i,1);
            i--;
        }
    }
}
updateEventMarker(event) {
    for (let i = 0; i < this._markers.length; i++) {
        if(this._markers[i].event.id == event.id) {
            this._markers[i].event = event;
            if (!event.lat || !event.lng){
                this._markers[i].marker.setLngLat([this.options.error_position.lng, this.options.error_position.lat]);
            } else {
                this._markers[i].marker.setLngLat([event.lng, event.lat]);
            }
        }
    }
}
clearEventMarkers() {
    for (let i = 0; i <this._markers.length; i++) {
        this._markers[i].marker.remove();
    }
    this._markers = [];
}
所有這些方法都應包含一個簡單的存儲系統,用于存儲已創建的標記,以便輕松更新和刪除地圖上的標記。在我們的例子中,它是通過this._markers數組完成的,該數組存儲有關標記和相關事件的信息。
要在網格區域中單擊事件時在地圖上顯示標記,您應該使用onEventClick(event)函數。在代碼中,它實現如下:
onEventClick(event) {
    // move to the marker on the map when the event is clicked in the description area
    if (this._markers && this._markers.length > 0) {
        for (let i = 0; i <  this._markers.length; i++) {
            const popup = this._markers[i].marker.getPopup();
            if (popup.isOpen()){
                popup.remove();
            }
            if (event.id ==  this._markers[i].event.id) {
                this._markers[i].marker.togglePopup();
                if (event.lat && event.lng) {
                    this.setView(event.lat, event.lng, this.options.zoom_after_resolve || this.options.initial_zoom);
                } else {
                    this.setView(this.options.error_position.lat, this.options.error_position.lng, this.options.zoom_after_resolve || this.options.initial_zoom);
                }
            }
        }
    }
}
步驟 6:調整地圖視圖顯示
MapTiler 的 API 允許精確控制地圖的顯示。例如,您可以使用 setView (latitude, longitude, zoom)方法將地圖視圖調整到由緯度和經度坐標確定的特定位置以及所需的縮放級別。因此,您可以設置所需的地圖焦點,確保最終用戶可以輕松查看和與相關地理信息交互。
setView(latitude, longitude, zoom) {
   this.map.setCenter([longitude, latitude]);
   this.map.setZoom(zoom);
}
如果數據庫未存儲事件的坐標,調度程序會自動為config中指定的事件設置默認位置。因此應該有resolveAddress(string)方法,該方法通過向指定的地理代碼發送請求從event.location屬性獲取事件的位置(lng,lat) 。
應該這樣實現:
async resolveAddress(string) {
    // get the position(lng,lat) of the event from event.location if the event doesn't have event.lat or event.lng
    let response = await fetch(`//api.maptiler.com/geocoding/${string}.json?key=${this.options.accessToken}`).then(response => response.json());
    let position = {};
    if (response && response.features.length) {
        position.lng = response.features[0].center[0];
        position.lat = response.features[0].center[1];
    } else {
        console.error(`Unable recieve a position of the event's location: ${string}`);
    }
    return position;
}
destroy()方法用于刪除地圖實例:
destroy(container) {
      this.map.remove();
      while (container.firstChild) {
         container.firstChild.remove();
      }
      container.innerHTML = "";
}
總而言之,maptilerAdapter.js 應該包含 9 種方法才能正確運行,如上所述。
步驟 7:將新的 Map 適配器添加到 Scheduler
最后一步是將新的地圖適配器添加到您的 JS 調度日歷中。為此,您需要導入模塊并將適配器添加到scheduler.ext.mapView.adapters ,并在scheduler.config.map_view_provider配置中指定其名稱。因此,調度程序配置將如下所示:
scheduler.config.header = [
    "day",
    "week",
    "month",
    "map",
    "date",
    "prev",
    "today",
    "next"
];
// activate the Map view extension
scheduler.plugins({
    map_view: true
});
scheduler.ext.mapView.adapters.maptiler = new maptilerAdapter(scheduler); // add new adapter to the extension
scheduler.config.map_view_provider = "maptiler"; // specify the map provider
scheduler.config.map_settings.accessToken = "8alNOUBUrHjEje2Qmkfc"; // specify the MapTiler API key.
scheduler.config.map_settings.initial_zoom = 8;
scheduler.locale.labels.map_tab = "Map";
scheduler.locale.labels.section_location = "Location";
scheduler.xy.map_date_width = 180; // date column width
scheduler.xy.map_description_width = 400; // description column width
scheduler.config.map_start = new Date(2019, 3, 1);
scheduler.config.map_end = new Date(2025, 9, 1);
scheduler.config.lightbox.sections = [
    { name: "description", height: 50, map_to: "text", type: "textarea", focus: true },
    { name: "location", height: 43, map_to: "event_location", type: "textarea" },
    { name: "time", height: 72, type: "time", map_to: "auto" }
];
scheduler.init('scheduler_here', new Date(2024, 5, 1), "map");
const mapEvents = [
    { "id": 278, "start_date": "2024-07-22 12:10:00", "end_date": "2024-07-22 12:15:00", "text": "Sudan", "event_location": "Janub Kurdufan, Sudan", "lat": 7.7172005929348435, "lng": 387.9898595809937 },
    { "id": 285, "start_date": "2024-08-01 02:40:00", "end_date": "2024-08-01 15:05:00", "text": "Ships", "event_location": "Australia", "lat": -28.08958685494885, "lng": 513.4549713134767 },
    { "id": 286, "start_date": "2024-09-15 00:00:00", "end_date": "2024-09-15 00:05:00", "text": "Argentina", "event_location": "Argentina", "lat": -33.288010117378505, "lng": 293.6837553977967 },
    { "id": 90, "start_date": "2024-09-16 00:00:00", "end_date": "2024-09-16 00:05:00", "text": "Berlin", "event_location": "Berlin", "lat": 52.523403, "lng": 13.411400 },
    { "id": 268, "start_date": "2024-07-22 11:35:00", "end_date": "2024-07-22 11:40:00", "text": "Brazil", "event_location": "Brazil", "lat": -15.813189304438533, "lng": -47.91412353515626 }
];
scheduler.parse(mapEvents);
這些是主要步驟,可讓您將基于 MapTiler 的自定義地圖適配器集成到您的 JavaScript 調度日歷中,就像在我們的示例中一樣。
結論
DHTMLX Scheduler 中的地圖視圖提供了事件調度的地理視角。通過添加自定義地圖適配器,我們的 JS 調度組件中的地圖視圖在選擇最適合項目需求的地圖選項方面提供了更大的靈活性。如果您是 DHTMLX Scheduler 的新手,但需要一個具有多種視圖(包括地圖視圖)的綜合調度工具來處理您的項目,歡迎下載試用體驗。
本站文章除注明轉載外,均為本站原創或翻譯。歡迎任何形式的轉載,但請務必注明出處、不得修改原文相關鏈接,如果存在內容上的異議請郵件反饋至chenjj@ke049m.cn
文章轉載自:慧都網