我正在使用 Mapbox-gl 在我的代码中显示地图
更新地图线并重新设置它们时,我收到此错误:
mapboxgl:已经有一个具有此 ID 的源
在设置图层和源之前,我将其删除
if (this.map.getLayer('mapLine')) {
this.map.removeSource('lines');
this.map.removeLayer('mapLine');
}
之后我正在做这个操作:
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'] },
});
但是,我在尝试添加图层时遇到错误。
线路是动态变化的还是只是为了测试?
当我需要来自 geojson 的动态更新数据时,我只需覆盖源即可。您的示例代码中的层并没有真正改变,对吧?您只想要新数据?
要更新源,您可以使用:
this.map.getSource('lines').setData(data);
然后在 addLayer 代码中检查它是否存在:
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'] },
});
}
希望这有帮助。如果您有疑问,请提问:)干杯