3

我正在使用 Google Maps API,目前已成功根据确切位置添加标记,但我还希望能够在国家/地区添加标记,而无需拥有该国家/地区的坐标。

这可能吗?

4

2 回答 2

14

确实很有可能。使用地理编码器:https ://developers.google.com/maps/documentation/javascript/geocoding

GeoCoder 可以返回一个国家的 lat / lngs,只需要知道它的名字。

假设你已经有一个map

geocoder = new google.maps.Geocoder();

function getCountry(country) {
    geocoder.geocode( { 'address': country }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
           map.setCenter(results[0].geometry.location);
           var marker = new google.maps.Marker({
               map: map,
               position: results[0].geometry.location
           });
        } else {
          alert("Geocode was not successful for the following reason: " + status);
        }
    });
}

getCountry('USA');
getCountry('Brazil');
getCountry('Denmark');

将在您的地图上放置标记,位于美国、巴西和丹麦的直接中心。

在此处输入图像描述

于 2013-09-11T15:22:06.683 回答
0

根据 Maps API,marker.position是必需属性,并且它必须是LatLng类型。所以至少你需要知道国家中心的坐标,或者你可以从中推断出中心坐标的国家的有界坐标数组。

我相信,如果您仅使用国家名称的地理编码器,该服务将为您提供该国家确切中心的坐标。我没有对此进行测试,我不知道如果您可以使用它有多少限制,但值得您将其作为您问题的解决方案进行检查。

例如:

var geo = new google.maps.Geocoder();
geo.geocoder.geocode('Spain', function (data) {
  // the coordinates are held in data[0].geometry.location.lat() and data[0].geometry.location.lng().
});
于 2013-09-11T15:16:44.357 回答