March 12, 2009

Zoom-To-Fit All Markers, Polylines or Polygons on A Google Map

The GLatLngBounds class in Google Maps API makes it easy to auto-center and auto-zoom a google map around a given set of latitude-longitude coordinates. The GLatLngBounds.getCenter() method returns the center point for the specified list of coordinates while GMap2.getBoundsZoomLevel() method returns the best-fit zoom level.

After calculating these two values, you can use the GMap2.setCenter() method or the GMap2.setCenter() and GMap2.setZoom() methods to set the center and zoom level.

Partial Example

// map: an instance of GMap2
// latlng: an array of instances of GLatLng
var latlngbounds = new GLatLngBounds();
for (var i = 0; i < latlng.length; i++) {
  latlngbounds.extend(latlng[i]);
}
map.setCenter(latlngbounds.getCenter(), map.getBoundsZoomLevel(latlngbounds));

The trick is to add the list of all points that need to be visible on the map simultaneously into a GLatLngBounds object. The Google Maps API can do the rest of the maths.

Example 1: Using Markers

This example uses an array of random GLatLng. This array is used to (1) create the markers and (2) center-zoom the map. View page source to see how this is done.

Example 2: Using Polylines and Polygons

GPolyline and GPolygon are merely arrays of GLatLng, so it is relatively straight forward to apply the same procedure on polylines and/or polygons. This example uses multidimensional arrays of GLatLng to create polylines and polygons. It then adds the content of all arrays into a single GLatLngBounds object. The remaining procedure is same as described above. View page source to see how this is done.

Visit the Google Maps API Reference page for complete details. To use these examples on your website, you must sign up for the Google Maps API.