I'm using OpenLayers 3 (v3.20). What I want to achieve is just to remove all features from a particular layer. I see that there is a clear method and documentation says, that
clear(opt_fast)
Remove all features from the source.
However, when I apply it to my layer source like so:
layer.getSource().clear();
I see a blink (features are removed) and then I see a server request, so that features are reloaded again. So, either documentation is incomplete, or there is a bug.
I also tried to remove features like so:
features = source.getFeatures();
for (i = 0; i < features.length; i += 1) {
source.removeFeature(features[i]);
}
But it works really strange. If, for example, I have four features, when I loop once, it removes just two features and when I loop twice, one extra feature is removed. All in all, I have to loop three times (which is indeed not DRY) to remove all features. I really wonder, why is that and how can I fix it. Thanks!
As pointed by Karl-Johan Sjögren, removing a array member when iterate through it modifies the array itself, so, you use reverse array or use a native function from Array MDN reference: