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
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.