3

I have a feature on the map in openlayers, my requirement is to allow the user to remove the feature by right click.

Here is the reference screenshots :

Hover on the feature

After right click

When user clicks on "Remove", the feature should be removed. If user clicks else where after the right click on feature, the "Remove" menu should disappear.

Here is the sample : openlayers map with a feature

capnam
  • 429
  • 9
  • 25
  • There is an extension too for contextmenu.[https://github.com/jonataswalker/ol-contextmenu] – capnam Mar 11 '19 at 04:39

1 Answers1

2

You will need to override the default content menu and add your own. Add listeners to turn it off if the view changes, the users hits the esc key, etc. Adding this code worked on your sample:

var contextMenu = document.createElement('div');
contextMenu.id = "contextMenu"
contextMenu.dir = "ltr";
contextMenu.className = "contextMenu";
contextMenu.style.position = "absolute";
contextMenu.style.left = "0px";
contextMenu.style.top = "0px";
contextMenu.style.display = "none";
map.getViewport().appendChild(contextMenu);

contextMenu.innerHTML = 
    '<div id="contextMenuRemove" class="menuItem" onclick="removeFeature();"> Remove </div>';

var mouseOver = false;

function hideContextMenu() {
    contextMenu.style.display = "none";
}

map.on('click', hideContextMenu);

map.getView().on('change', function () {
    if (contextMenu.style.display != "none") {
       setTimeout(hideContextMenu, 250);  // delay reset until map singleclick event has fired
    }
});

contextMenu.addEventListener('contextmenu', function (e) {
    e.preventDefault();
});

document.addEventListener('keydown', function (e) {
    if (e.keyCode == 27) {
        hideContextMenu();
    }
});

function openContextMenu(x, y) {
    contextMenu.style.right = "";
    contextMenu.style.bottom = "";
    contextMenu.style.left = x + "px";
    contextMenu.style.top = y + "px";
    contextMenu.style.display = "block";
}

var canvas = map.getViewport().getElementsByTagName("canvas")[0];
var features;

canvas.addEventListener('contextmenu', function (e) {
    features = map.getFeaturesAtPixel([e.x, e.y]);
    if (features) {
        e.preventDefault();
        openContextMenu(e.x, e.y);
    }
});

function removeFeature() {
    source.removeFeature(features[0]);
}

This is the style I use for context menus (in your case there were no disabled entries or separators)

.contextMenu {
    background-color: #eee;
    position: absolute;
    border: solid 1px black;
    width: 100px;
}
.contextMenu .menuItem {
    cursor: pointer;
    padding: 5px;
}
.contextMenu .disabled {
    color: #aaa;
    pointer-events: none;
    cursor: none;
}
.contextMenu .menuItem:hover {
    background-color: #ccc;
}
.menuSeparator {
    border-bottom: solid 1px black;
}";
Mike
  • 16,042
  • 2
  • 14
  • 30