Joe Kueser's Blog Another Geek Finding His Place on the Web

17Mar/108

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:

  1. var bounds = new google.maps.LatLngBounds();

Next loop through and create points however you normally would, adding the bounds.extend(latlng) you see:

  1. for (var index in marker_array) {
  2.     var lat = marker_array[index].lat;
  3.     var lng = marker_array[index].lng;
  4.     var latlng = new google.maps.LatLng(lat, lng);
  5.     bounds.extend(latlng);
  6. }

Finally, tell the map to do all the heavy lifting with the fitBounds() method:

  1. 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!

Filed under: Google, JavaScript 8 Comments