简体   繁体   中英

Getting map coordinates from Leaflet.js?

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM