Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 302
shabda Avatar asked Aug 09 '13 11:08

shabda


People also ask

How do you get the current zoom level in leaflet?

You can get the current zoom level using getZoom().

How is zoom level calculated?

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).


2 Answers

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] /*, ...*/ ]);
like image 180
Pwnosaurus Avatar answered Sep 28 '22 02:09

Pwnosaurus


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.

like image 26
tyr Avatar answered Sep 28 '22 02:09

tyr