Google Maps: Zoom Level, Center from points on map
So you’ve created a pretty Google Map on your website. You place a whole heap of markers on your map, driven from data you’ve got stored in your database.
A nice thing to do when we first show the map, would be to ensure that all the markers are visible on the map.
To do this, we need to set the zoom level and center point of the map dynamically. So how do we do this? The answer is GLatLngBounds():
// Get your locations from the database
var mapLocations = <? echo json_encode(Locations::Find()) ?>;
// Initialise our map, add some controls and a default center point
var map = new GMap2(document.getElementById("Mall_Map"));
map.setCenter(new GLatLng(15, 20), 2);
map.addControl(new GLargeMapControl());
map.addControl(new GMapTypeControl());
// Now the fun part - create a GLatLngBounds object
var bounds = new GLatLngBounds();
//
for (var i=0; i<mapLocations.length; i++)
{
var location = mapLocations[i];
var point = new GLatLng(location.Latitude, location.Longitude);
// createMarker() is a custom function which returns a marker for a given GLatLng
var marker = createMarker(point);
// extend our bounds to include this point
bounds.extend(point);
// add our marker
map.addOverlay(marker);
}
// Now dynamically set the center and zoom level for our map based on our bounds!
map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
The key is the use of the line:
map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
This uses our bounds (which we’ve dynamically extended to include each of our points) to determine what the center and bounds zoome level should be.

August 15th, 2009 at 3:25 am
Классная статья!