简体   繁体   中英

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??

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);

I had a similar issue. The repeated calls to setVisible did not work for me.

Turns out if you remove a selected feature from a layer, it will be removed, but it will still be visible. And it won't be removed "Visually" until you select something else.

What I did:

// collection that will contain all selected features
var selectFeatures = new ol.Collection();
// setting up the select interaction
var selectInteraction = new ol.interaction.Select({
  features: selectFeatures
});

// custom event to clear all selections
selectInteraction.on('clearSelections', function() {
   selectedFeatures.clear();
});



removeSomeFeaturesFromLayer() {
   // dispatch the event first
   selectInteraction.dispatchEvent({
      type: 'clearSelections'
   });

   /* 
    * NOW LOOP THROUGH THE FEATURES IN THE LAYER
    * AND REMOVE WHATEVER ONES YOU WANT
    */

}

I hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM