Reputation: 1145
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.
Upvotes: 5
Views: 5087
Reputation: 53185
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/
Upvotes: 10
Reputation: 1145
In the end, this is actually quite simple, though not united into one function. First, you need to create a Leaflet bounds object:
var bounds = new L.LatLngBounds();
Then, for each marker on the map:
bounds.extend(markerObject.getLatLng());
Finally, apply the new bounds to the map:
mapObject.fitBounds(bounds);
Upvotes: 3