Anand
Anand

Reputation: 139

Get latlng of the map when panned or zoomed

I am trying to get the lat lng of the map center when it's dragged, panned or zoomed. I want to get the instant update of lat lng of the map's center the moment I drag, pan or zoom the map. I am using the following code

map.on('focus', function(e) {
   console.log("Lat, Lon : " + e.latlng.lat + ", " + e.latlng.lng)
});

I get the error Cannot read property 'lat' of undefined. But the code works when I use clickinstead of focus.

This can be easily done with google map using

map.addListener('get_center',function(){
  console.log("Lat, Lng:"+ map.center.lat()","+ map.center.lng())
})

Does anyone know a proper way to do it in the leaflet

Upvotes: 1

Views: 95

Answers (1)

Elango Dhandapani
Elango Dhandapani

Reputation: 116

You need to use getCenter() method to get the lat and lng at anytime. Use the zoom and drag events as you prefer. Refer the documentation. Make sure you use getCenter() as below

map.on('dragend', function(e) {
    console.log('Lat: ' +  map.getCenter().lat + ' Lng: ' + map.getCenter().lng);
});

Upvotes: 2

Related Questions