Finding center and zoom level in leaflet, given a list of lat-long pairs

gis, javascript, leaflet, openstreetmap

Solution

The easiest way is with a `LatLngBounds` object. You can then have the map fitBounds. Or get its center manually if you prefer.

var myPoints = [[1,1],[2,2] /*, ...*/ ];
var myBounds = new L.LatLngBounds(myPoints);
myMap.fitBounds(myBounds); //Centers and zooms the map around the bounds

You can even forgo instantiating the bounds object if you would like:

myMap.fitBounds([[1,1],[2,2] /*, ...*/ ]);

Problem

I have a list of lat long pairs. (Or I could create GeoJSON). I want to map them all on leaflet map. How do I find what should I set as the center and as the zoom level so that all the points show up. All the leaflet examples seem to use a fixed center and zoom, but I am accepting user input so I need to calculate them.

Original source