Leaflet.js center the map on a group of markers

Solution 1:

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.