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

7
我曾经为此苦苦挣扎。问题在于,我可能会在一个样式上绘制几个不同的图层,然后调用setStyle(例如进入卫星视图),这将清除我所有的图层。
1个回答

11
我通过复制我关心的图层和源文件并重新应用它们来解决了它。

我解决这个问题的方法是复制我关心的层和源,然后重新应用它们。

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

2
感谢@Toli!在Mapbox的git上,对于这个功能的请求已经无人回应了一年以上。你的解决方案是我找到的唯一适用于我的用例的东西!你太棒了! - Paul J
2
哇,6年过去了,问题还是一样。太糟糕了。 - Andries

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接