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

有没有根据地图的中心大小自动设置缩放级别?

maps.google.com正是我所需要的,所以,例如,如果我search俄罗斯,我会得到一个缩放级别,使俄罗斯适合在屏幕上,当我search古巴时,我得到一个更高的缩放级别,以便古巴只是适合。

是否有某种方法可以将Maps Api设置为国家/地区,并获得适当的缩放级别。

如果没有,我想我将不得不手动(唉!)创build我自己的表的这个信息。 或者这个信息是免费提供的?

对于API v3请检查下面的答案。

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

// 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); 

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

放大俄罗斯和古巴

对于V3这个代码为我工作:

 var geocoder = new google.maps.Geocoder(); geocoder.geocode( { 'address': address}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { map.setCenter(results[0].geometry.location); map.fitBounds(results[0].geometry.viewport); } }); 

如果你不使用谷歌地图API,只使用他们的地理编码,你可以使用这个公式:

 var url = 'http://maps.google.com/maps/geo?q=YOUR_QUERY&output=json&oe=utf8&sensor=false&key=YOUR_KEYback=geoCodeDone'; jQuery.getScript(url); function geoCodeDone(data) { if (data.Status.code == 200) { lng = data.Placemark[0].Point.coordinates[0]; lat = data.Placemark[0].Point.coordinates[1]; var east = data.Placemark[0].ExtendedData.LatLonBox.east; var west = data.Placemark[0].ExtendedData.LatLonBox.west; var zoom = 11 - Math.round(Math.log(Math.abs(west-east))/Math.log(2)); } } 

如果您不想使用谷歌地理编码客户端,由于使用限制,您可以使用自己的列表。 你可以从这个github回购一个 。

以下是使用jQuery的getJSON函数和google maps API v3的代码示例:

  function initialize() { // read the list of countries $.getJSON('countries.json', function (countries) { // will use the country with index 40 (Cyprus) var index_country = 40; var myOptions = { center: new google.maps.LatLng( countries[index_country].center_lat, countries[index_country].center_lng), } var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); // set the bounds of the map var bounds = new google.maps.LatLngBounds( new google.maps.LatLng(countries[index_country].sw_lat, countries[index_country].sw_lng), new google.maps.LatLng(countries[index_country].ne_lat, countries[index_country].ne_lng) ); map.fitBounds(bounds); }); }