How to solve error: "mapboxgl: There is already a source with this ID when updating layer"?
Asked Answered
Z

1

5

I am using Mapbox-gl for showing the map in my code

When updating map lines and re-setting them I am getting this error:

mapboxgl: There is already a source with this ID

Before setting layer and source I am removing it

if (this.map.getLayer('mapLine')) {
  this.map.removeSource('lines');
  this.map.removeLayer('mapLine');
}

After that I am doing this operations:

this.map.addSource('lines', {
    type: 'geojson',
    data: {
      type: 'FeatureCollection',
      features,
    },
  });
  this.map.addLayer({
    id: 'mapLine',
    type: 'line',
    source: {
      type: 'geojson',
      data: {
        type: 'FeatureCollection',
        features,
      },
    },
    paint: { 'line-width': 4, 'line-color': ['get', 'color'] },
  });

However, I am getting errors when trying to add a layer.

Zabaglione answered 6/1, 2021 at 14:21 Comment(0)
B
6

Are the lines dynamically changing or do you just do it for testing?

When I need dynamic updated data from a geojson I just overwrite the source. The Layer doesn't really change in your example code right? You just want the new Data?

To Update the source you can use:

this.map.getSource('lines').setData(data);

Then in the addLayer code just check if it exists or not with:

if (!this.map.getLayer('mapline')) {
this.map.addLayer({
    id: 'mapLine',
    type: 'line',
    source: {
      type: 'geojson',
      data: {
        type: 'FeatureCollection',
        features,
      },
    },
    paint: { 'line-width': 4, 'line-color': ['get', 'color'] },
  });
}

Hope this helps. If you have questions just ask :) cheers

Bramble answered 8/1, 2021 at 11:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.