phonegap geocoder.geocode从结果中获取门牌号码

时间:2016-11-07 13:16:05

标签: javascript android cordova google-maps

我有这个地理编码器代码:

function codeLatLng(lat, lng) {
 geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(lat, lng);
    geocoder.geocode({'latLng': latlng}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
      console.log(results)
        if (results[1]) {
         //formatted address
         alert(results[0].formatted_address)//this is a string of all location 

        } else {
          alert("No results found");
        }
      } else {
        alert("Geocoder failed due to: " + status);
      }
    });
  }

我想将街道和门牌号码保存在不同的变量中,我该怎么做?

1 个答案:

答案 0 :(得分:1)

根据the documentation,您可以从地理编码API响应中获取formatted_address,而不是获取address_components,然后获取street_number

"address_components" : [
    {
       "long_name" : "1600",
       "short_name" : "1600",
       "types" : [ "street_number" ]
    },
    ...
]

您可以获取迭代address_components的所需组件(我在此示例中检索street_number):

for (var i = 0; i < results[0].address_components.length; i++) {
    var address_components = results[0].address_components[i];
    if (address_components.types[0] == 'street_number') {
        console.log(address_components.long_name);
    }
}