问题
I'm trying to use Leaflet to get the map coordinates of somewhere a user has right clicked. I've been going through the Leaflet API and so far I've figured out that I need to listen to the contextmenu event and use mouseEventToLatLng method to get the coordinates when clicked. However, when I go through and debug my code I'm not seeing an accessible latLng variable anywhere. Did I miss understand something in the API?
function setMarkers() {
document.getElementById("transitmap").addEventListener("contextmenu", function( event ) {
// Prevent the browser's context menu from appearing
event.preventDefault();
var coords = L.mouseEventToLatLng( event );
});
};
回答1:
What you want to get is mousemove event. This is basically how you do it,
var lat, lng;
map.addEventListener('mousemove', function(ev) {
lat = ev.latlng.lat;
lng = ev.latlng.lng;
});
document.getElementById("transitmap").addEventListener("contextmenu", function (event) {
// Prevent the browser's context menu from appearing
event.preventDefault();
// Add marker
// L.marker([lat, lng], ....).addTo(map);
alert(lat + ' - ' + lng);
return false; // To disable default popup.
});
回答2:
The coordinates of the right click event should be directly available as latlng property of the event argument of the "contextmenu" listener.
map.on("contextmenu", function (event) {
console.log("Coordinates: " + event.latlng.toString());
L.marker(event.latlng).addTo(map);
});
Demo: http://plnkr.co/edit/9vm81YsQxnkAFs35N8Jo?p=preview
来源:https://stackoverflow.com/questions/37516184/getting-map-coordinates-from-leaflet-js