Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

281
Visualizações
Opción de eliminación de elementos de Openlayers con el botón derecho del mouse

Me gustaría habilitar la opción de eliminar después de hacer clic derecho en mi objeto. Hasta ahora, el código que proporcioné no funciona porque el navegador está verificando algunos dispositivos por mí, como puede ver a continuación:

ingrese la descripción de la imagen aquí

Mi código se ve así:

 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 }

Me gustaría tener una opción para eliminar el objeto seleccionado después del clic derecho. ¿Cómo puedo hacerlo?

ACTUALIZAR:

Encontré una opción bastante buena para lograrlo:

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

lo que me llevó a una conclusión como esta:

 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(), }

basado también en la solución aquí:

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

pero hasta ahora hago clic derecho y la consola muestra el "menú contextual" solo para mí.

Mi JSfiddle completo está aquí:

https://jsfiddle.net/1x3nuspj/

¿Qué estoy haciendo mal aquí?

Gracias y Saludos

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Aquí hay un ejemplo de trabajo

 <!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/

about 4 years ago · Juan Pablo Isaza Relatório

0

¿Necesita eliminar el último elemento? Solo desea borrar el mapa correctamente. Aquí mencioné el último elemento solo claro mientras hacía clic con el botón derecho.

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

Enlace de demostración

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda