如何让 Google Maps API 为一个国家设置正确的缩放级别?

问题描述:

有没有根据地图所在国家/地区的大小自动设置缩放级别的功能?

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 正是我所需要的,因此,例如,如果我搜索俄罗斯,我会得到一个缩放级别,俄罗斯刚好适合屏幕,而当我搜索古巴时,我会得到更高的缩放级别,所以古巴正好适合.

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.

是否有某种方法可以为 Maps Api 提供国家/地区位置并获得适当的缩放级别.

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?

对于 API v3,请检查这个答案.

您可以使用 Google 地图客户端地理编码器 获取国家的边界​​框,如下例所示:

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

// API version 2
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));
});

// API version 3
// ... set north, south, east and west ...
var bounds = new google.maps.LatLngBounds(new google.maps.LatLng(south, west), 
                                          new google.maps.LatLng(north, east));
map.fitBounds(bounds);

下面的截图显示了上述技术在搜索俄罗斯和古巴时的结果:

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