Pan and Zoom to Include All Markers in Google Maps v3
I had what I thought was a pretty common and simple problem to solve. I wanted to make sure that all of the markers I placed on my Google map were initially visible. So the map would have to pan to the center of all of the points and then zoom in or out to fill the view port.
There were a ton of examples on how to do this with v1 and v2 of the Google maps API, but, alas, I was using v3, and I wasn’t able to find even a hint as to how to do this. Through trial and error and a lot of actual reading of the API docs, I finally figured it out. Hopefully this will help someone else someday. (Sorry if you are using v4 or v5 and this doesn’t work, blame Google
)
First create an empty LatLngBounds:
-
var bounds = new google.maps.LatLngBounds();
Next loop through and create points however you normally would, adding the bounds.extend(latlng) you see:
-
for (var index in marker_array) {
-
var lat = marker_array[index].lat;
-
var lng = marker_array[index].lng;
-
var latlng = new google.maps.LatLng(lat, lng);
-
bounds.extend(latlng);
-
}
Finally, tell the map to do all the heavy lifting with the fitBounds() method:
-
this.map.fitBounds(bounds);
There are plenty of tutorials out there to tell you how to create the points, markers, and the map, so I won’t bother going into that here.
Hope that helps someone!
Works great.
I spent 2 days looking for how to do this with v3. Thank you for saving me the time to dig through the API doc
Glad to help. It’s not perfect (it sometimes seems to zoom out too far) but seems to work.
Thank, does partially the trick… Does not zoom in though…
Yeah, I’ve noticed that too. I haven’t tried it yet, but I think you can get around this by either setting the initial zoom way in, as it seems to zoom out OK. If you get something working, please let me know, I’ll be fixing that bug in my code “soon”.
Hey dude, thanks for sharing that with us! Unfortunately I got the same problem with the zoom out… actually, every time I call the function it seems to zoom out a bit more until I’ve reached a world-wide view… well, I’ll tell if I find a way…
Ok, I found the solution (at least for my case; maybe you can take advantage of it as well):
Every time I wanted to call bounds.extend() I did this:
bounds = map.getBounds();
bounds.extend(point);
map.fitBounds(bounds);
But map.getBounds() retrieves an object containing the bounds of the viewing area, not of the markers. So you never should call map.getBounds but work with a separate bounds-object which was only in “contact” with the coordinates of the markers.
Hope, you understand what I mean
Thanks, this is exactly what I need!
Thanks for the codez, worked wicked for me!