5

I want to clear my vector layer features, I did it before in OpenLayers 2 with destroyFeatures(); command, I research many times but I can't do that in OL4. How can I do that?

My OpenLayers 2 code:

    if (self.selectFeatureLayer) { self.selectFeatureLayer.destroyFeatures(); }
    if (self.markerLayer) { self.markerLayer.clearMarkers(); }
    if (self.layerRuler) { self.layerRuler.destroyFeatures(); }
    if (self.measureControls) {
        if (self.measureControls.line.active) {
            self.measureControls.line.deactivate();
            self.measureControls.line.activate();
        }
        if (self.measureControls.polygon.active) {
            self.measureControls.polygon.deactivate();
            self.measureControls.polygon.activate();
        }
    }

2 Answers 2

6

layer.getSource().clear() function doesn't work properly. You can try removeFeature(feature) method of ol.source.Vector. I wrote a sample for this issue:

 var vectorLayer = new ol.layer.Vector({
  source: new ol.source.Vector({
    url: 'https://openlayers.org/en/v4.2.0/examples/data/geojson/countries.geojson',
    format: new ol.format.GeoJSON()
  })
});

var map = new ol.Map({
  layers: [
    new ol.layer.Tile({
      source: new ol.source.OSM()
    }),
    vectorLayer
  ],
  target: 'map',
  view: new ol.View({
    center: [0, 0],
    zoom: 1
  })
});

map.on('click', function(evt) {

    var features = vectorLayer.getSource().getFeatures();
    features.forEach((feature) => {
        vectorLayer.getSource().removeFeature(feature);
    });
});

Sample url: Click on map to see it.

I wrote under map on click. You can write whereever you want.

5

First get the source of your layer, and then call the clear method to remove all features from the layer:

layer.getSource().clear()
3
  • I am trying now but I get this error: "Cannot read property 'clear' of null", Could it be because the source is empty? Commented Aug 11, 2017 at 12:15
  • Are you sure the layer you are trying this on has a vector source?
    – bartvde
    Commented Aug 11, 2017 at 15:19
  • I am sure its type Vector but I am not assign any source yet, for now its empty. Commented Aug 11, 2017 at 19:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.