Martín Verzilli

Martín Verzilli

Positioning a Google Map according to a set of coordinates

4 min
Sep 5 2008
mapping, coding
4 min
Sep 5 2008

The Google Maps API provides a number of methods to make it easier to accomplish this task. One only has to take the time to explore them and think how to combine them to get the solution.

It's not a hard thing to do, but in case you're a lazy guy, here goes a short snippet which given an array of GLatLng objects will zoom the map to let you see all those coordinates, and pan it so that the center matches the center of the smallest rectangle that contains all of them.

map.checkResize();

var latlngs = getLatlngs();

var latlngBounds = new GLatLngBounds();

for (var i = 0; i < latlngs.length; i++){
   latlngBounds.extend(latlngs);
}

map.setZoom(map.getBoundsZoomLevel(latlngBounds) < MAXIMUM_AUTO_ZOOM_LEVEL ?
   map.getBoundsZoomLevel(latlngBounds) : MAXIMUM_AUTO_ZOOM_LEVEL);

map.panTo(latlngBounds.getCenter());

Let's assume "map" holds a GMaps2 instance, "getLatLngs()" returns the set of coordinates we want to use and "MAXIMUM_AUTO_ZOOM_LEVEL" is an integer.

GLatLngBounds is a class of the Google Maps API which represents a rectangle in the map, being its limits defined by GLatLng objects. This class provides a method "extend" which makes the bounds object enlarge enough to surround the given coordinates.

The method getBoundsZoomLevel in GMaps2 returns the maximum zoom level which we'd need to set in order to be able to see the complete rectangle represented by the given bounds object.

So we create a bounds object which surrounds all the coordinates, get which level of zoom we would need to see it completely, then pan to the center of it.

The constant (or variable, whatever) MAXIMUM_AUTO_ZOOM_LEVEL is to avoid zooming to much when we only have one coordinate (or few of them rather close to each other). If the point is in the middle of the sea and you don't do this, you'll just see the sea's sky-blue. Of course, you may want this behavior.

Finally, the call to checkResize() in GMaps2. That shouldn't be necessary, but I found (totally empirically) it depends on where you host the map. In the case which inspired this post, I was hosting it in an ExtJS GMapPanel inside an ExtJS Viewport. It used to work in unexpected ways, the map would stay uncentered or the zoom level would be incorrect. Then I realized that if I resized the browser's window, it began to work. Going back to the checkResize() method, it makes the map check if there was a resize of its parent. If that's the case, it adjusts itself to fit the new size. Adding that line at the beginning of the snippet made it work, so I guess the problem may be due to the order in which the different parts of the application are rendered (which somehow results in an inconsistent state of the map).

Martin