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) => {}
})
}