Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to remove all layers from a map

I have a big map application, so to be representative I will have to provide just a chunk of code. So, this is how I try to remove all layers from a map:

map.getLayers().forEach(function (layer) {
    map.removeLayer(layer);
});

//map.getOverlays().clear(); <-- also tried this, but to no effect

And I have some random behaviour - sometimes all layers are removed, sometimes not. It's a complete randomness, so there is no guarantee, that you will be able to reproduce this issue. So, it may be enough for me to know just conceptually, why it may happen.

SOLUTION

This is obviously an ol3 bug, because if I loop and delete just twice, then it starts working:

map.getLayers().forEach(function (layer) {
    map.removeLayer(layer);
});
//for some crazy reason I need to do it twice.
map.getLayers().forEach(function (layer) {
    map.removeLayer(layer);
});

Probably, it's not a bug, and there is some secret method, that enables to clear the map. But I do not know about it.

like image 402
Jacobian Avatar asked Nov 29 '16 09:11

Jacobian


1 Answers

This is not a bug. The reason why your code does not work is because you are modifying the layers collection while looping through it. Doing so changes the index of each layer, and will cause unexpected results.

The proper way to clear all layers of a map is to use ol.Map#setLayerGroup():

map.setLayerGroup(new ol.layer.Group());
like image 52
ahocevar Avatar answered Sep 20 '22 21:09

ahocevar