4

Looking at the OpenLayers 3 ol.source.Vector docs, I can see that there exists a method ol.Vector.removeFeature(feature).

Does this mean the best way to remove all the features from a vector layer would be something like this...?

var iter = layer.getFeatures().values();
while (!(entry = iter.next()).done) { 
    layer.removeFeature(entry.value); 
}

Or is there better way?

11

Ok let's try again.

If you look closer at the docs you will see that ol.source.Vector has a clear method that you can use to remove all the features from the source.

See http://openlayers.org/en/v3.0.0/apidoc/ol.source.Vector.html#clear

This is how you will use that method:

vectorSource.clear()
  • Ah! Must have scrolled by that one. Thanks @erilem! – sfletche Nov 23 '14 at 5:35
  • I have been using .clear for removing features from the source but now I get an error: "Uncaught TypeError: Array.prototype.forEach called on null or undefined" it is a clear error; however, checking the source shows that the source already has objects in it and also is not undefined: >>console.info(source.getFeatures());>>[Bn, Bn] ;>>console.info(source); >>W {fa: false, da: undefined, jb: Gc, Hd: W, Ma: null…}... any idea why it spits such an error? – msc87 Jun 21 '16 at 10:39

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.