Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
708 views
in Technique[技术] by (71.8m points)

angular - How to solve error: "mapboxgl: There is already a source with this ID when updating layer"?

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Is 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);

Than 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...