簡體   English   中英

Mapbox GL setData 更新圖層

[英]Mapbox GL setData to update layer

在我的 angular 應用程序中,我正在使用方向 api 並嘗試添加從一個方向到另一個方向的路線路徑。 第一次制作 ajax 請求路由路徑時創建正確,但從第二次開始我看不到路由路徑。

從 ajax 請求開始,我第二次收到此錯誤 - 此 map 上已存在 ID 為“路由”的層

有沒有辦法更新mapbox中的源和圖層?

drawRoute() {
const url = `https://api.mapbox.com/directions/v5/mapbox/driving/${this.startData?.lng},${this.startData?.lat};${this.endData?.lng},${this.endData?.lat}?alternatives=true&geometries=geojson&steps=true&access_token=${environment.mapbox.accessToken}`;

this._http.get(url).subscribe({
    next: (result) => {
        const geojson: any = {
            type: 'Feature',
            properties: {},
            geometry: {
               type: 'LineString',
               coordinates: result.routes[0]
            }
        };

        if (this.map?.getSource('route')) {
            const source: mapboxgl.GeoJSONSource = this.map?.getSource('route') as 
             mapboxgl.GeoJSONSource;
            source.setData(geojson);
        } else {
            this.map?.addSource('route', {
            type: 'geojson',
                data: {
                    type: 'Feature',
                    properties: {},
                    geometry: {
                       type: 'LineString',
                       coordinates: result.routes[0].geometry.coordinates
                    }
                }
            });
        }

        this.map?.addLayer({
            id: 'route',
            type: 'line',
            source: 'route',
            layout: {
                'line-join': 'round',
                'line-cap': 'round'
            },
            paint: {
              'line-color': '#1F5ED8',
              'line-width': 2
            }
        });
    },
    error: (err) => {} 
})
}

我認為您正在尋找可用於 Mapbox GL JS 中 GeoJSON 源的setData()方法。 該方法允許您更新基礎源數據並觸發 map 重新渲染。 然后,數據驅動的樣式應該會啟動並根據需要為您的更新層設置樣式。

https://docs.mapbox.com/mapbox-gl-js/api/sources/#geojsonsource#setdata

這是一個偽代碼示例

map.getSource("source-id").setData(updatedGeoJSONData);

希望這可以幫助。 我一直在為您可能感興趣的 Mapbox 編寫一系列指南:以下是一些鏈接:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM