68

I'm using Leaflet.js and would like some way to centre the map on the markers I have so that all are within the user's view when the page launches. If all the markers are clustered in a small area, I would like the map to zoom down to a level that still displays all of them.

I know google maps has an auto-centre function but how would I go about this with Leaflet.js?

1 Answer 1

149

You can use L.LatLngBounds in order to create an area to zoom to.

First, create a bounds and pass it an array of L.LatLngs:

var bounds = new L.LatLngBounds(arrayOfLatLngs);

This will create a bounds that will encapsulate every point that is contained in the array. Once you have the bounds, you can fit the bounds of the map to match your created bound:

 map.fitBounds(bounds);

This will zoom the map in as far as it can go, while still containing every point in your array.

Alternatively, you can also call the fitBounds method by simply calling it and passing in an array of L.LatLng objects. For example:

map.fitBounds([[1,1],[2,2],[3,3]]);

This would function exactly the same, without the need to create a specific L.LatLngBounds object.

4
  • This works, though with fit bounds you might've mentioned that the bounds you need are north west and south east. For future reference anyone using this, you will have to find the max and min values for both latitude and longitude on your markers.
    – lorless
    Commented Jun 24, 2013 at 16:17
  • 13
    L.LatLngBounds has two constructors. One of them is what you describe - two points, northwest and southeast. The second constructor, however, takes an array of L.LatLngs of any size. Additionally, you can call L.LatLngBounds.extend() in order to increase the size of an existing bounds. Using either of these two options, you should never have to greater than/less than checks to manually increase the size of the bounds yourself.
    – Patrick D
    Commented Jun 24, 2013 at 16:41
  • 2
    Excellent answer and thank you for following up on comment questions, as the explanation helped to better understand the functionality (even 3 years later)
    – redfox05
    Commented Apr 26, 2016 at 5:57
  • 2
    @redfox05 even 7 years later :D
    – davidenke
    Commented Feb 4, 2020 at 11:35

Not the answer you're looking for? Browse other questions tagged or ask your own question.