Monday, December 29, 2008

Zoom to points on Google Maps

If you have implemented a Google map, placed custom GPoints on it, and want to automatically zoom to best fit these points, try the following javascript:

function fitMap(map, points) {
   var bounds = new GLatLngBounds();
   for (var i=0; i< points.length; i++) {
      bounds.extend(points[i]);
   }
   map.setZoom(map.getBoundsZoomLevel(bounds));
   map.setCenter(bounds.getCenter());
}

Where "map" is the global map variable that is needed already by your Google Maps API code, and where "points" is an array of GLatLng() points; like so:

var zoompoints = new Array();
zoompoints = [];
zoompoints[0] = new GLatLng(longitude,latitude);
zoompoints[1] = new GLatLng(longitude,latitude);

fitMap(map, zoompoints);


Where "longitude" and "latitude" are the custom longitude and latitude you want for your individual points.

No comments: