RAHUL KUNDU
RAHUL KUNDU

Reputation: 955

Mapbox GL setData to update layer

In my angular app I am using directions api and trying to add a route path from one direction to another. On the first time when making the ajax request route path is creating properly but from the second time i can not see the route path.

I am getting this error from second time onwards of the ajax request - Layer with id "route" already exists on this map

Is there any way to update the source and layer in 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) => {} 
})
}

Upvotes: 5

Views: 10520

Answers (1)

tylerben
tylerben

Reputation: 516

I think that the setData() method that is available for GeoJSON sources in Mapbox GL JS is what you are looking for. The method allows you to update the underlying source data and triggers a map re-render. The data-driven styling should then kick in and style your updates layers as desired.

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

Here is a pseudo-code example

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

Hope this helps! I have been writing a series of guides for Mapbox that you might be interested in too. Here are some links:

Upvotes: 9

Related Questions