Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 error.

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,
  subdomains:['mt0','mt1','mt2','mt3']
}).addTo(map);

map.locate({
  setView: true, 
  maxZoom: 16, 
  watch:false, 
  timeout: 60000,
  enableHighAccuracy: true
});
var marker; 
var circles;

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

  if(map.hasLayer(circles) && map.hasLayer(marker)) {
    map.removeLayer(circles);
    map.removeLayer(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();;

  map.addLayer(marker);
  map.addLayer(circles);

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

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

But when i change this console.log(mylat); to this console.log(result);, 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 console.log(result);:

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

Could someone please advise on this?

Thanks in advance.

like image 474
Jackson Avatar asked Mar 11 '23 16:03

Jackson


1 Answers

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.

like image 189
IvanSanchez Avatar answered Mar 20 '23 12:03

IvanSanchez