Mapbox GL setData to update layer
Asked Answered
H

1

5

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) => {} 
})
}
Hoehne answered 27/3, 2021 at 8:39 Comment(0)
R
9

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:

Ryeland answered 31/3, 2021 at 20:2 Comment(1)
this definitely worked for me! thanks.Mousey

© 2022 - 2024 — McMap. All rights reserved.