March 15, 2011

Zoom-to-Fit All Markers on Google Map v3

Google Maps API version 3, like its predecessor, allows you to automatically center and zoom the map around a set of coordinates. This is useful when you add markers or other overlays to a Google map programmatically; the API can center and zoom the map optimally so that all overlays are visible at once glance.

Compared to the Google Maps API v2 example, API v3 makes the process simpler and more logical via the Map.fitBounds() method.

Partial Example

// map: an instance of google.maps.Map object
// latlng: an array of google.maps.LatLng objects
var latlngbounds = new google.maps.LatLngBounds();
for (var i = 0; i < latlng.length; i++) {
  latlngbounds.extend(latlng[i]);
}
map.fitBounds(latlngbounds);

The trick is to add all points that into a google.maps.LatLngBounds object using the extend() method. The Google Maps API does the necessary panning and zooming when you call Map.fitBounds()method.

Example 1: Using Markers

This example adds a couple of markers to a map which is initially centered at (0, 0) and zoomed at level 0. The coordinates of the markers are later used to extend a google.maps.LatLngBounds object, which is eventually passed to the Map.fitBounds() method. View page source to see how this is done.

Example 2: Using Polygons

This example adds a couple of polygons to a map which is initially centered at (0, 0) and zoomed at level 0. A polygon itself is just an array of coordinates that define a shape. We therefore use nested loops to extend a google.maps.LatLngBounds object with all coordinates of all polygons. View page source to see how this is done.

Note: at the time of writing, there is no Polygon.getBounds() method, which could have eliminated the need of nested loops. Also note that API v3 makes it is possible to define complex polygons as an array of array of coordinates. This is not covered in the above example.