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

Tol*_*oli 1 mapbox mapbox-gl-js

我为此奋斗了很多。面临的挑战是,我可能会在一种样式上绘制几个不同的图层,然后调用setStyle(例如进入卫星视图),这会抹掉我所有的图层。

Tol*_*oli 5

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

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);
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢@托利!一年多来,mapbox git 中对此功能的请求一直没有得到答复。您的解决方案是我为我的用例找到的唯一有效的解决方案!你摇滚! (2认同)
  • 哇,六年过去了,还是同样的问题。太糟糕了。 (2认同)