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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With