Getting map coordinates from a flyer

I am trying to use the Flyer to get the coordinates of the map where the user right-clicked. I went through the Leaflet API and still realized that I needed to listen for the contextmenu event and use the mouseEventToLatLng method to get the coordinates when clicked. However, when I look through and debug my code, I do not see the latLng variable available anywhere. Am I missing an understanding of something in the API?

 function setMarkers() { document.getElementById("transitmap").addEventListener("contextmenu", function( event ) { // Prevent the browser context menu from appearing event.preventDefault(); var coords = L.mouseEventToLatLng( event ); }); }; 
+7
javascript leaflet
source share
2 answers

What you want to get is a 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 context menu from appearing event.preventDefault(); // Add marker // L.marker([lat, lng], ....).addTo(map); alert(lat + ' - ' + lng); return false; // To disable default popup. }); 
+6
source share

Right-click event coordinates must be directly accessible as the 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

+3
source share

All Articles