代码之家  ›  专栏  ›  技术社区  ›  Toli

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

  •  1
  • Toli  · 技术社区  · 7 年前

    我和这个斗争了很久。挑战是,我可以在一个样式上画几个不同的层,然后调用 setStyle (例如:去卫星视图)这会抹去我所有的图层。

    1 回复  |  直到 7 年前
        1
  •  5
  •   Toli    7 年前

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

    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);
    }
    
    推荐文章