Following this question:
Deleting selected feature in OpenLayers?
I would like to have also an option to delete the object by the mouse right-click.
I found an option for switching on the context menu:
How can I select a feature in Openlayers 3 by right click it?
and tried to combine it with my example by using this code
https://rawgit.com/jonataswalker/ol-contextmenu/master/examples/contextmenu.js
in order to have some small popup after right-click on the selected object with the delete option.
Finally I've built the code like this:
var deleteFeature = function(evt){
var rightcl = document.getElementById('map').oncontextmenu = function(e){
e = e?e:window.event;
if (e.preventDefault) e.preventDefault(); // For non-IE browsers.
else return false; // For IE browsers.
};
if(evt.keyCode == 46){
var selectCollection = selectInteraction.getFeatures();
if (selectCollection.getLength() > 0) {
vectorLayer.getSource().removeFeature(selectCollection.item(0));
}
} else if (rightcl) {
var selectCollection = selectInteraction.getFeatures();
if (selectCollection.getLength() > 0) {
vectorLayer.getSource().removeFeature(selectCollection.item(0));
}
};
};
document.addEventListener('keydown', deleteFeature, false);
which doesn't work at all.
I tried to define the right-click event by using this example:
http://spatialnotes.blogspot.com/2010/11/capturing-right-click-events-in.html
and include it as an internal variable. In this case, the right-click would work normally for the whole map, but it could run the pop-up or simply delete the selected feature.
Is there any chance to resolve it?
My full JSfiddle is here:
Best Answer
Problem with your code is that you are setting right click processing inside the event listener
deleteFeature
, so it's set up only after delete is pressed. You should catch right click outsidedeleteFeature
event listener, on the same global level.Code could then look something like this: