OpenLayers – How to Remove All Layers from Map Except Base Map Layer

basemaplayersopenlayers

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:

basemap = new TileLayer({ source: new OSM() })

new Map({
  layers: [ basemap ],
  controls: [
    new Zoom({ zoomInLabel: '', zoomOutLabel: '' })
  ],
  view: new View({
    center: proj.fromLonLat([center.lon, center.lat]),
    zoom
  }),
  target: div
});

Then in your forEach, you can do an if to conditionally delete only the layers that are not equal to the basemap variable.

Alternatively, when removing all other layers you could avoid the forEach loop by simply re-defining the map's layers to be: [ basemap ]

Related Question