Zoom To Fit All Markers on Google Maps API v3

I’d like a problem that for once hasn’t already been solved by someone else.

I had a set of markers which needed to be all on screen, and for some reason there’s no .zoomToShow method. Fortunately it’s pretty simple to create yourself.

//  Make an array of the LatLng's of the markers you want to show
var LatLngList = array (new google.maps.LatLng (52.537,-2.061), new google.maps.LatLng (52.564,-2.017));
//  Create a new viewpoint bound
var bounds = new google.maps.LatLngBounds ();
//  Go through each...
for (var i = 0, LtLgLen = LatLngList.count(); i < LtLgLen; i++) {
  //  And increase the bounds to take this point
  bounds.extend (LatLngList[i]);
}
//  Fit these bounds to the map
map.fitBounds (bounds);

And that’s pretty much it. Then, of course, I found that someone had already done this before, but for version two of the API.

This entry was posted in Programming and tagged . Bookmark the permalink.

5 Responses to Zoom To Fit All Markers on Google Maps API v3

  1. Larry Kubin says:

    Just wanted to send you a quick thanks for this little snippet. My version which was much longer stopped working in version 3 — this one is much simpler.

  2. fly2279 says:

    Do you know of a way to zoom to fit all markers while keeping the center of the map at a certain lat/long or marker?

  3. Tiaan says:

    Thanks for the code snippet, it worked beautifully with the new marker cluster (V3)

  4. LatLngList.count() was throwing an error at me, I changed it to LatLngList.length and everything appears to be working.

  5. Phil says:

    Thanks for explaining this so clearly – it was exactly what I was looking for!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>