7
votes

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.

2

2 Answers

15
votes

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] /*, ...*/ ]);
2
votes

I'd recommend to use GeoJSON and create your leaflet map as described in the tutorial. Than you can simply use geojsonLayer.getBounds() together with map.setBounds() to zoom to your data.