Leaflet.js center the map on a group of markers

LeafletMarkers

Leaflet Problem Overview


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?

Leaflet Solutions


Solution 1 - Leaflet

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionlorlessView Question on Stackoverflow
Solution 1 - LeafletPatrick DView Answer on Stackoverflow