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.
You can get the current zoom level using getZoom().
Distance per pixel math As tiles are 256-pixels wide, the horizontal distance represented by one pixel is: Spixel = Stile / 256 = C ∙ cos(latitude) / 2. For example on the equator and at zoom level 0, we get 40 075 016.686 / 256 ≈ 156 543.03 (in meters per pixel).
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] /*, ...*/ ]);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With