Getting map coordinates from Leaflet.js?

可紊 提交于 2020-05-10 04:08:34

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!