Roy
Roy

Reputation: 1518

How do I get the latlng after the dragend event in leaflet?

I'm trying to update the lat/lng value of a marker after it is moved. The example provided uses a popup window to display the lat/lng.

I have a "dragend" event listener for the marker, but when I alert the value of e.latlng it returns undefined.

javascript:

function markerDrag(e){
    alert("You dragged to: " + e.latlng);
}

function initialize() {
    // Initialize the map
    var map = L.map('map').setView([38.487, -75.641], 8);
    L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>',
        maxZoom: 18
    }).addTo(map);

    // Event Handlers
    map.on('click', function(e){
        var marker = new L.Marker(e.latlng, {draggable:true});
        marker.bindPopup("<strong>"+e.latlng+"</strong>").addTo(map);

        marker.on('dragend', markerDrag);
    });
}


$(document).ready(initialize());

http://jsfiddle.net/rhewitt/Msrpq/4/

Upvotes: 24

Views: 30205

Answers (5)

Kedar.Aitawdekar
Kedar.Aitawdekar

Reputation: 2454

Use e.target.getLatLng() to get the latlng of the updated position.

// Script for adding marker on map click
function onMapClick(e) {

    var marker = L.marker(e.latlng, {
             draggable:true,
             title:"Resource location",
             alt:"Resource Location",
             riseOnHover:true
            }).addTo(map)
              .bindPopup(e.latlng.toString()).openPopup();

    // #12 : Update marker popup content on changing it's position
    marker.on("dragend",function(e){

        var changedPos = e.target.getLatLng();
        this.bindPopup(changedPos.toString()).openPopup();

    });
}

JSFiddle demo

Upvotes: 24

gouder hicham
gouder hicham

Reputation: 133

if anyone is using react than you should use :

const map = useMap()
map.addEventListener("dragend" , ()=> {
const {lat , lng} = map.getCenter()
})

Upvotes: 0

Aral Roca
Aral Roca

Reputation: 5929

I think the API changed.

Nowadays is: const { lat, lng } = e.target.getCenter();

Upvotes: 10

user2441511
user2441511

Reputation: 11116

While using e.target._latlng works (as proposed by this other answer), it's better practice to use

e.target.getLatLng();

That way we're not exposing any private variables, as is recommended by Leaflet:

Private properties and methods start with an underscore (_). This doesn’t make them private, just recommends developers not to use them directly.

Upvotes: 10

lintu
lintu

Reputation: 1102

latlng value is not in e.latlng but in e.target._latlng . Use console.

Upvotes: 15

Related Questions