Jackson Jackson - 1 year ago 89
Javascript Question

How to get the LatLng of a "dragend" event in Leaflet?

I'm trying to get the lat and long of a dragged and dropped marker on the Leaflet map.

However, I'm constantly getting

TypeError: event.latlng is undefined

This is my entire code:

var map = L.map('map');

googleStreets = L.tileLayer('http://{s}.google.com/vt/lyrs=m&x={x}&y={y}&z={z}',{
maxZoom: 20,

setView: true,
maxZoom: 16,
timeout: 60000,
enableHighAccuracy: true
var marker;
var circles;

function onLocationFound(e) {
var radius = e.accuracy / 2;

if(map.hasLayer(circles) && map.hasLayer(marker)) {

marker = new L.Marker(e.latlng, {draggable:true});
circles = new L.circle(e.latlng, radius);
circles.bindPopup("You are within " + radius + " meters from this point").openPopup();;


marker.on('dragend', function(event) {
var mylat = event.latlng.lat
var result = marker.getLatLng();

when I see inside the console, I see that error.

But when i change this
to this
, I see the lat and long in the console but the format of them is not what I am looking for.

This is what I get in the console when i drag and drop the marker the code with this

Object { lat=51.564025924107554, lng=0.7077598571777344, equals=function(), more...}

Could someone please advise on this?

Thanks in advance.

Answer Source

You're listening to a L.Marker's dragend event. If you look at the documentation for that, you'll see that dragend events fire event handlers which receive a DragEndEvent, which only has distance, type and target properties. No latlng. That's expected.

Now, the target property of a DragEndEvent is the L.Marker instance. So:

  • You do not want the LatLng of the DragEndEvent, because it doesn't even exist
  • You want the LatLng of the L.Marker which is the target of the DragEndEvent.

And how do you get the LatLng of a L.Marker? With its getLatLng() method. So:

marker.on('dragend', function(event) {
  var latlng = event.target.getLatLng();
  console.log(latlng.lat, latlng.lng)

See a working example.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download