如何在Openlayers 5中右键单击删除功能

时间:2019-03-08 09:06:57

标签: javascript contextmenu openlayers openlayers-5

我在openlayers中的地图上有一个地图项,我的要求是允许用户通过右键单击来删除地图项。

以下是参考屏幕截图:

Hover on the feature

After right click

当用户单击“删除”时,应删除该功能。 如果用户在右键单击功能后单击其他位置,则“删除”菜单应消失。

以下是示例:openlayers map with a feature

1 个答案:

答案 0 :(得分:2)

您将需要覆盖默认的内容菜单并添加自己的菜单。添加侦听器以在视图发生更改,用户按下esc键等时将其关闭。添加此代码可对您的示例起作用:

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]);
}

这是我用于上下文菜单的样式(在您的情况下,没有禁用的条目或分隔符)

.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;
}";