53

I have a leaflet map that pans and zooms. How can I dynamically get the lat/long of the edges of the map (after zooming in/out + panning)?

bernie2436
  • 22,841
  • 49
  • 151
  • 244
  • 2
    Do you mean the bounds/extents of the map? Or every lat long that runs around the border of the extents? If you just want to get the bounds you can call a map.getBounds() on dragend. map.on('dragend', myFunctionThatGetsMapBounds()) I would try something like this for getting the bounds every time the map is moved. Same can be done for zoomend. – Ju66ernaut Apr 08 '14 at 21:54

2 Answers2

86

It is, as you may guess:

map.getBounds();

If you want to get the bounds after panning and zooming, use events, like

map.on('moveend', function() { 
     alert(map.getBounds());
});
bernie2436
  • 22,841
  • 49
  • 151
  • 244
tmcw
  • 11,536
  • 3
  • 36
  • 45
  • 4
    for more information about getBounds, it returns a LatLngBounds. Methods and props there : https://www.wrld3d.com/wrld.js/latest/docs/leaflet/L.LatLngBounds/ – Bill Somen Oct 09 '20 at 06:01
30

The above answer is correct, but not very helpful and unfortunately, the leaflet docs don't give much detail about the getBounds() call.

If you add this to your map init function, you can see the map data displayed:

map.on('dragend', function onDragEnd(){
    var width = map.getBounds().getEast() - map.getBounds().getWest();
    var height = map.getBounds().getNorth() - map.getBounds().getSouth();

    alert (
        'center:' + map.getCenter() +'\n'+
        'width:' + width +'\n'+
        'height:' + height +'\n'+
        'size in pixels:' + map.getSize()
    )});

Note that size is the pixel dimensions of the map window, where the bounds are the scaled internal sizes. Try zooming and you will see that the size stays constant, but the height and with doubles for each level of zoom.

There are a whole bunch of methods that live under the LatLngBounds object, so you should be able to find one of the calls there that can give you whatever info you are looking for.

Aswin Murugesh
  • 10,831
  • 10
  • 40
  • 69
Roger Hill
  • 3,677
  • 1
  • 34
  • 38