Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zoom to Fit All Markers on LeafletJS Map

After adding a series of markers to a LeafletJS map, is it possible to get Leaflet to zoom and realign it's focus to show every marker? I see many similar questions to do with Google Maps but none for Leaflet.

Something like:

map.fitAllMarkers();

I've also noticed several functions in Leaflet to get the bounds of the map, but I'm not sure how to employ those to the desired effect.

like image 718
Laef Avatar asked Jul 02 '16 01:07

Laef


1 Answers

You could also take advantage of the purposely made featureGroup.getBounds() method to have the map fitting the extent of your markers:

var fg = L.featureGroup([arrayOfMarkers]).addTo(map);

map.fitBounds(fg.getBounds());

Demo: http://jsfiddle.net/3v7hd2vx/28/

like image 70
ghybs Avatar answered Oct 03 '22 04:10

ghybs