1

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.

2

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 ]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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