首页 > 解决方案 > 在 Mapbox 中,使用 setStyle 时如何保留图层?

问题描述

我为此奋斗了很久。挑战在于,我可能会在一种样式上绘制几个不同的图层,然后调用setStyle(例如:转到卫星视图)来清除我所有的图层。

标签: mapboxmapbox-gl-js

解决方案


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

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

推荐阅读