[GIS] Remove selected feature Openlayers 3

openlayers

I'm using openlayers 3 to create web application that allow to user to draw LineString features in the map.
this is the code:

var raster = new ol.layer.Tile({
source: new ol.source.MapQuest({ layer: 'sat' })
});


var source = new ol.source.Vector();

var vector = new ol.layer.Vector({
    name: 'my_vectorlayer',
    source: source,
    style: new ol.style.Style({
        stroke: new ol.style.Stroke({
            color: '#ffcc33',
            width: 5
        })
    })
});

var map = new ol.Map({
    layers: [raster, vector],
    target: document.getElementById('map'),
    view: new ol.View2D({
        center: [-11000000, 4600000],
        zoom: 4
    })

});
var draw;
function addInteraction() {
 map.removeInteraction(singleClick);
    draw = new ol.interaction.Draw({
        source: source,
        type: ("LineString")
    });
    map.addInteraction(draw);
}

by the previous code i can drow lines in to the map. the drawn lines will be added to vector layer. I wont when the user select one of the line that he draw can remove them.
this is the code of selecting the feature:

var singleClick = new ol.interaction.Select();
function addSelect() {
    map.removeInteraction(draw);
    map.addInteraction(singleClick);
}

and it's work very will, enter image description here

I just want the user to be able to remove the selected LineString…

Best Answer

Yes, you can remove selected feature.

var draw;
var featureID = 0;
var singleClick;
var selectedFeatureID;

// First some change in this function.

function addInteraction() {
   map.removeInteraction(singleClick);

      draw = new ol.interaction.Draw({
      source: source,
      type: ("LineString")
  });

 // Create drawend event of feature and set ID to feature

  draw.on('drawend', function (event) {
    featureID = featureID + 1;
    event.feature.setProperties({
        'id': featureID
    })
 })
   map.addInteraction(draw);
 }

Then Change in select Function as follow:

 function addSelect() {
    map.removeInteraction(draw);
    singleClick = new ol.interaction.Select();
    map.addInteraction(singleClick);

     singleClick .getFeatures().on('add', function (event) {
     var properties = event.element.getProperties();
     selectedFeatureID = properties.id;       
    });
 }

Then call this function on REMOVE button click

 function removeSelectedFeature() {
   var features = source.getFeatures();
     if (features != null && features.length > 0) {
         for (x in features) {
            var properties = features[x].getProperties();
            console.log(properties);
            var id = properties.id;
            if (id == selectedFeatureID) {
              source.removeFeature(features[x]);
               break;
            }
          }
        }
      }

With this code you can remove any selected feature. If it is Line,Point, Polygon etc.