What i need is to delete all layers from the map without removing the base one (in my case OSM)
Here is some code
new Map({
layers: [
new TileLayer({ source: new OSM() }) // <== the one i dont want to be removed
],
controls: [
new Zoom({ zoomInLabel: '', zoomOutLabel: '' })
],
view: new View({
center: proj.fromLonLat([center.lon, center.lat]),
zoom
}),
target: div
});
I can iterate over them with a forEach
and applying map.removeLayer(layer);
but i can't distinguish it with the other layers.
Best Answer
Assign your basemap layer to a variable, and in the map layers, include the layer by variable rather than creating in in-place:
Then in your
forEach
, you can do anif
to conditionally delete only the layers that are not equal to thebasemap
variable.Alternatively, when removing all other layers you could avoid the
forEach
loop by simply re-defining the map's layers to be:[ basemap ]