I would like to delete my feature in OpenLayers by the "del" button. I found some solutionss here:
How to delete a feature in Openlayers 3.8.2 with `del` Key
and combined it with the hint here:
var deleteFeature = function(evt){
if(evt.keyCode == 46){
vectorLayer.getSource().clear();
if (selectInteraction) {
selectInteraction.getFeatures().clear();
}
}
};
document.addEventListener('keydown', deleteFeature, false);
but I just want to delete only the selected feature by the "del" button. Instead of it all are gone.
I tried to put instead:
var deleteFeature = function(evt){
if(evt.keyCode == 46){
vectorLayer.getSource().removeFeature(SelectedFeature);
}
};
document.addEventListener('keydown', deleteFeature, false);
but it looks like the removeFeature(SelectedFeature)
; doesn't work here
I tried also this solution:
https://github.com/openlayers/openlayers/issues/4214
but it didn't work either.
My full JS fiddle is here:
https://jsfiddle.net/z08kfcg7/
which includes pure .js only
How can I delete only one feature selected instead of all of them?
UPDATE:
I tried also:
var selectInteraction = new ol.interaction.Select({
condition: ol.events.condition.click,
wrapX: false
})
var deleteFeature = function(evt){
if(evt.keyCode == 46){
selectInteraction.getFeatures().clear();
}
};
document.addEventListener('keydown', deleteFeature, false);
Nothing happens, just the feature previously selected is unselected now.
UPDATE:
function removeSelectedFeature() {
var features = selectInteraction.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) {
selectInteraction.removeFeature(features[x]);
break;
}
}
}
}
var deleteFeature = function(evt){
if(evt.keyCode == 46){
removeSelectedFeature();
};
};
document.addEventListener('keydown', deleteFeature, false);
this one doesn't work either.
Remove selected feature Openlayers 3
UPDATE III
var deleteFeature = function(evt){
if(evt.keyCode == 46){
vectorLayer.getSource().removeFeature(selectInteraction.getFeatures());
};
};
document.addEventListener('keydown', deleteFeature, false);
This piece of code throws an error:
Uncaught TypeError: Cannot read properties of undefined (reading 'forEach') at e.removeFeatureInternal (Vector.js:906) at e.removeFeature (Vector.js:896) at HTMLDocument.deleteFeature (qgis2web.js:913)
selectedFeature
to that feature and then usevectorLayer.getSource().removeFeature(selectedFeature);
to delete it at the time of key press.