在Mapbox中,使用setStyle时如何保留图层?

在Mapbox中,使用setStyle时如何保留图层?,mapbox,mapbox-gl-js,Mapbox,Mapbox Gl Js,我为此奋斗了相当长一段时间。挑战是,我可能会在一种样式上绘制几个不同的图层,然后调用setStyle(例如:转到卫星视图),它会清除我所有的图层。我通过复制我关心的图层和源并重新应用它们来解决这个问题 function forEachLayer(text, cb) { this.map.getStyle().layers.forEach((layer) => { if (!layer.id.includes(text)) return; cb(layer); })

我为此奋斗了相当长一段时间。挑战是,我可能会在一种样式上绘制几个不同的图层,然后调用
setStyle
(例如:转到卫星视图),它会清除我所有的图层。

我通过复制我关心的图层和源并重新应用它们来解决这个问题

function forEachLayer(text, cb) {
  this.map.getStyle().layers.forEach((layer) => {
    if (!layer.id.includes(text)) return;

    cb(layer);
  });
}
// Changing the map base style
export function changeStyle(style) {
  const savedLayers = [];
  const savedSources = {};
  const layerGroups = [
    'layer-type-1',
    'layer-type-2'
  ];

  layerGroups.forEach((layerGroup) => {
    this.forEachLayer(layerGroup, (layer) => {
      savedSources[layer.source] = this.map.getSource(layer.source).serialize();
      savedLayers.push(layer);
    });
  });

  this.map.setStyle(`mapbox://styles/mapbox/${style}`);


  setTimeout(() => {
    Object.entries(savedSources).forEach(([id, source]) => {
      this.map.addSource(id, source);
    });

    savedLayers.forEach((layer) => {
      this.map.addLayer(layer);
    });
  }, 1000);
}

谢谢@Toli!mapbox git中对该功能的请求已经一年多没有得到响应。您的解决方案是我为我的用例找到的唯一有效的东西!你太棒了!哇,六年过去了,还是一样的问题。太糟糕了。