14

我正在使用 Google Maps API (v2) 并希望将加载的地图集中到一个国家/地区(例如英国)。

目前我使用以下方法将地图居中:

map.setCenter(new GLatLng( 43.907787,-79.359741), 9);

但这显然需要经度和纬度。

有什么办法可以通过插入国家名称来做到这一点?

4

3 回答 3

17
var country = "United States"
var map = new GMap2($("#map")[0]);
map.setUIToDefault();

var geocoder = new GClientGeocoder();
geocoder.getLatLng(country, function (point) {
  if (!point) {
    // Handle error
  } else {
    map.setCenter(point, 8, G_PHYSICAL_MAP);
  }
});
于 2009-11-16T19:46:08.673 回答
10

您需要先对地址进行地理编码:

var geocoder = new google.maps.Geocoder();
var location = "England";
geocoder.geocode( { 'address': location }, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
        map.setCenter(results[0].geometry.location);
    } else {
        alert("Could not find location: " + location);
    }
});
于 2012-08-31T17:47:41.753 回答
5

像这样将位置名称或地址转换为纬度/经度称为地理编码。Google Maps API 现在包含此功能:请参阅http://code.google.com/apis/maps/documentation/services.html#Geocoding

它们包括一个示例应用程序,您可以在其中输入地址,并且只需输入国家名称即可。我不知道他们是否要去该国的确切中心。

于 2009-11-16T19:30:21.530 回答