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
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);
}
-
2Thanks @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 JCommented May 13, 2019 at 16:18
-
3