Bounding Box in Google Maps
Normally when you initialize a new Google map you set the coordinates for the center of the map and manually specifies the initial zoom level. Sometimes, however, there’s a need to dynamically calculate the center point and zoom level for certain content to fit into the viewport.
Let’s say that you have a number of markers on a map and you want the map to be displayed so that they all fit inside the viewport. You could of course experiment with center point and zoom levels to get it right. But what if the markers are put there dynamically so you don’t know beforehand where they’ll show up?
That’s where this trick will come in handy.
Using a Bounding Box
First you have to calculate the bounding box. That is, the coordinate for the south-west and north-east corners. In this case the coordinates for the marker that’s most south and the marker that’s most west provides the coordinates for the south-west corner. And vice versa for the north-east corner.

Now that you know the coordinates you just have to create a GLatLngBounds object, define it’s coordinates and serve it to GMap2.setCenter().
GLatLngBounds takes two optional arguments. A GLatLng for the south-west corner and a GLatLng for the north-east corner.
GMap2.getBoundsZoomLevel() calculates the appropriate zoom level to fit the bounding box in the available viewport. It also adds some extra padding around the box.
map = new GMap2(document.getElementById("map"));
// Define the two corners of the bounding box
var sw = new GLatLng(59.0, 13.12);
var ne = new GLatLng(60.35, 16.90);
// Create a bounding box
var bounds = new GLatLngBounds(sw, ne);
// Center map in the center of the bounding box
// and calculate the appropriate zoom level
map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
I was shown this technique by my good friend Fredrik Jonsson, who writes about programming on freddes.se.
My Google Maps book
If you found this article useful you might be interested in my book Beginning Google Maps API 3. It covers everything you need to know to create awesome maps on your web sites. Buy it on Amazon.com
About the author
Gabriel Svennerberg is an independent Interaction/UI Designer and Web Developer living in Sweden. When he's not busy building web application designed for humans, he writes about all things web on his site In usability we trust. Gabriel is the author of the book Beginning Google Maps API 3 published by Apress.-
Mathias
-
Alan
-
http://www.svennerberg.com Gabriel Svennerberg
-
Alan
-
http://www.svennerberg.com Gabriel Svennerberg
-
http://aiskahendra.blogspot.com Aiska
-
http://www.svennerberg.com Gabriel Svennerberg
-
http://aiskahendra.blogspot.com Aiska
-
http://www.svennerberg.com Gabriel Svennerberg
-
http://bendtheblock.wordpress.com Alex O’Byrne
-
http://bendtheblock.wordpress.com Alex O’Byrne
-
gopi
-
Toleti S
-
http://grapsus.net/ Grapsus
-
http://buy-kinect.org/ buy kinect
-
Naresh