Search code examples
javascriptopenlayers-3

Unable to remove feature in OpenLayers 3


I have read dozens of threads at stackoverflow, but none of them helps. So, this is what I try to do:

features.forEach(function(feature){
    source.removeFeature(feature); 
    console.log("removed");
    console.log(feature);
});

As a result, when I have only one feature selected, I see in the console these messages:

removed Controller.js:525:8
Object { disposed_: false, onDisposeCallbacks_: undefined, ...}

In terms of what I see in the console, everything looks good. But the problem is that the feature is not removed from the map.

EDIT

Now it is even more interesting. If I convert features to array with getArray and do this:

 for(var i=0,len=features.length;i<len;i++){
    var feature = features[i];
    source.removeFeature(feature);
 }
 source.clear();

when I have a lot of features and only one feature selected, then in this case only this selected feature remains and all the rest features are removed. What the heck is going on??


Solution

  • I had this issue for a long time and I could not figure it out. As it turns out, it seems to be a refresh issue in OpenLayers. The way I found to get the layer to refresh is to make it invisible and then visible again.

    Here is the code I used to solve the problem (in AngularJS):

    vectorLayer.getSource().removeFeature(feature);
    $timeout(function() {
        vectorLayer.setVisible(false);
        vectorLayer.setVisible(true);
    }, 10);
    

    If you're not using Angular, just use the following:

    vectorLayer.getSource().removeFeature(feature);
    vectorLayer.setVisible(false);
    vectorLayer.setVisible(true);