Openlayers通过鼠标右键单击删除元素选项

Openlayers delete element option by mouse rightclick

我想在右键单击我的对象后启用删除选项。到目前为止,我提供的代码不起作用,因为浏览器正在为我检查一些设备,如下所示:

我的代码如下所示:

 var polygonInteraction = new ol.interaction.Draw({
 type: 'Polygon',
 source: vectorLayer.getSource()
 });
  polygonInteraction.setActive(false);
  polygonInteraction.on('drawend', onDrawend);
  polygonInteraction.on('drawend', function(e) {
  var title = prompt("Please provide the name", "default");
  var value = prompt("Please provide the value", "undefinied");
  var id = x++
  e.feature.setProperties({
  'Id': id,
  'Name': title,
  'Value': value,
 });
 
 function Rightcl(e) {
  var rightclick;
  if (e) var e = window.event;
  if (e.which) rightclick = (e.which == 3);
  else if (e.button) rightclick = (e.button == 2);
  alert('Delete me' + rightclick); // true or false
 }

我希望有一个选项可以在右键单击后删除所选对象。我该怎么做?

更新:

我找到了一个很好的实现方法:

https://gis.stackexchange.com/questions/148428/how-can-i-select-a-feature-in-openlayers-3-by-right-click-it

这让我得出这样的结论:

 console.info('contextmenu');
  var feature = map.forEachFeatureAtPixel(map.getEventPixel(e),
   function (feature, layer) {
       return feature;
    });
  
   if (feature) {
   selectInteraction.getFeatures()
   }
   return removeFeature
   });


   var removeFeature = {
   text: 'Remove this object',
   classname: 'marker',
   callback: selectInteraction.getFeatures(),
   }

也基于此处的解决方案:

https://rawgit.com/jonataswalker/ol-contextmenu/master/examples/contextmenu.js

但到目前为止,我进行了右键单击,控制台只为我显示“上下文菜单”。

我的完整 JSfiddle 在这里:

https://jsfiddle.net/1x3nuspj/

我做错了什么?

感谢和问候

这是一个工作示例

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.9.0/css/ol.css" type="text/css">
    <style>
      .map {
        height: 400px;
        width: 100%;
      }
    </style>
    <script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.9.0/build/ol.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/ol-contextmenu@latest/dist/ol-contextmenu.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/ol-contextmenu"></script>
    <title>OpenLayers example</title>
  </head>
  <body>
    <h2>My Map</h2>
    <div id="map" class="map"></div>
    <script type="text/javascript">
      var map = new ol.Map({
        target: 'map',
        layers: [
          new ol.layer.Tile({
            source: new ol.source.OSM()
          })
        ],
        view: new ol.View({
          center: ol.proj.fromLonLat([4.35247, 50.84673]),
          zoom: 4
        })
      });
    </script>
  </body>
</html>
var contextmenu = new ContextMenu({
  width: 170,
  defaultItems: true, // defaultItems are (for now) Zoom In/Zoom Out
  items: []
});



var removeMarker = function (obj) {
  layer.getSource().removeFeature(obj.data.marker);
};
var removeMarkerItem = {
  text: 'Remove this Marker',
  icon: 'img/marker.png',
  callback: removeMarker
};

var restore = false;
contextmenu.on('open', function (evt) {
  var feature = map.forEachFeatureAtPixel(evt.pixel, function (ft, l) {
    return ft;
  });
  if (feature) {
    contextmenu.clear();
    removeMarkerItem.data = { marker: feature };
    contextmenu.push(removeMarkerItem);
    restore = true;
  } else if (restore) {
    contextmenu.clear();
    contextmenu.extend(contextmenu_items);
    contextmenu.extend(contextmenu.getDefaultItems());
    restore = false;
  }
});

var layer = new ol.layer.Vector({
     source: new ol.source.Vector({
         features: [
             new ol.Feature({
                 geometry: new ol.geom.Point(ol.proj.fromLonLat([4.35247, 50.84673]))
             })
         ]
     })
 });
map.addLayer(layer);
map.addControl(contextmenu);

https://jsfiddle.net/dab4Lvnz/5/

您是否需要删除最后一项只想清除地图的权利。这里我提到了最后一项只能在右键单击时清除。

var drawingManager;
var selectedShape;
var all_overlays = [];
var gmarkers = Array();
var polygons = Array();
function setSelection(shape) {
  clearSelection();
  selectedShape = shape;
  shape.setEditable(true);
}
function clearSelection() {
  if (selectedShape) {
    selectedShape.setEditable(false);
    selectedShape = null;
  }
}
function initialize() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 10,
    center: new google.maps.LatLng(33.619003, -83.867405),
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    disableDefaultUI: true,
    zoomControl: true
  });
  var polyOptions = {
    fillColor: '#0099FF',
    fillOpacity: 0.7,
    strokeColor: '#AA2143',
    strokeWeight: 2,
    editable: true
  };
  // Creates a drawing manager attached to the map that allows the user to draw Polygons
  drawingManager = new google.maps.drawing.DrawingManager({
    drawingControlOptions: {
      drawingModes: [
        google.maps.drawing.OverlayType.POLYGON
      ]
    },
    polygonOptions: polyOptions,
    map: map
  });

  google.maps.event.addListener(drawingManager, 'overlaycomplete', function (e) {
    calcIntersection(e.overlay, all_overlays);
    all_overlays.push(e.overlay);
  });
  
  google.maps.event.addListener(map, "rightclick", function(event) {
   all_overlays[ all_overlays.length - 1].setMap(null);
   all_overlays.pop();
});

}

function calcIntersection(newOverlay, allOverlays) {
  //ensure the polygon contains enought vertices 
  if(newOverlay.getPath().getLength() < 3){
     alert("Not enought vertices. Draw a polygon that contains at least  3 vertices.");
     return;
  }

  var geometryFactory = new jsts.geom.GeometryFactory();
  var newPolygon = createJstsPolygon(geometryFactory, newOverlay);

  //iterate existing polygons and find if a new polygon intersects any of them
  var result = allOverlays.filter(function (currentOverlay) {
    var curPolygon = createJstsPolygon(geometryFactory, currentOverlay);
    var intersection = newPolygon.intersection(curPolygon);
    return intersection.isEmpty() == false;
  });

  //if new polygon intersects any of exiting ones, draw it with green color
  if(result.length > 0){
     newOverlay.setOptions({strokeWeight: 2.0, fillColor: 'green'});    
  }
}



function createJstsPolygon(geometryFactory, overlay) {
  var path = overlay.getPath();
  var coordinates = path.getArray().map(function name(coord) {
    return new jsts.geom.Coordinate(coord.lat(), coord.lng());
  });
  coordinates.push(coordinates[0]);
  var shell = geometryFactory.createLinearRing(coordinates);
  return geometryFactory.createPolygon(shell);
}


google.maps.event.addDomListener(window, 'load', initialize);

演示 Link