Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Mapbox how do I preserve layers when using setStyle?

I battled with this for quite a bit. The challenge is, I might draw a few different layers on one style, and then call setStyle (ex: going to satellite view) which wipes out all of my layers.

like image 238
Toli Avatar asked Aug 27 '18 00:08

Toli


1 Answers

I solved it by copying the layers and sources I cared about and reapplying them

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);
}
like image 193
Toli Avatar answered Nov 10 '22 09:11

Toli