7

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.

1 Answer 1

12

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);
}
2
  • 2
    Thanks @Toli ! The requests for this functionality in the mapbox git have gone unanswered for over a year. Your solution is the only thing I've found for my use case which works! You rock!
    – Paul J
    Commented May 13, 2019 at 16:18
  • 3
    Wow, 6 years onwards and still the same issues. Too bad.
    – Andries
    Commented Aug 7, 2019 at 13:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.