views:

1168

answers:

1

Is there a was of automatically setting the zoom level based on the size of the country that the map has been centered on?

maps.google.com does exactly what I need, so, for example, if I search for Russia I get a zoom level such that Russia just fits on screen, and when I search for Cuba I get a higher zoom level so that Cuba just fits.

Is there some way of giving the Maps Api a country location and getting an appropriate zoom level.

If not, I guess that I would have to manually (ugh!) create my own table for this information. Or is this information freely available somewhere?

+4  A: 

You can use the Google Maps Client-side Geocoder to get the bounding box of the country, as in the following example:

var geocoder = new GClientGeocoder();

geocoder.getLocations("Russia", function (locations) { 

    var north = locations.Placemark[0].ExtendedData.LatLonBox.north;
    var south = locations.Placemark[0].ExtendedData.LatLonBox.south;
    var east  = locations.Placemark[0].ExtendedData.LatLonBox.east;
    var west  = locations.Placemark[0].ExtendedData.LatLonBox.west;

    var bounds = new GLatLngBounds(new GLatLng(south, west), 
                                   new GLatLng(north, east));

    map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
});

The screenshots below show the results of the above technique when searching for Russia and Cuba:

Zoom on Russia and Cuba

Daniel Vassallo
Excellent, that was perfect thanks. I'm working in GWT and it can't yet access ExtendedData, so I had to create some JSNI methods to do that. One thing that got me for a while: make sure the map is visible when calling getBoundsZoomLevel, otherwise it returns a zoom level of zero.
krishnaz
@krishnaz: Good job. Thanks for sharing the `getBoundsZoomLevel()` tip.
Daniel Vassallo
+1 What an age we live in........
Pekka
Awsome answer, +1
mdrozdziel