简体   繁体   中英

phonegap geocoder.geocode get the house number from results

I have this geocoder code:

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

I want to save the street and house number in a different variables, how can I do that?

According to the documentation , instead of getting the formatted_address you can get the address_components from the Geocoding API response, and then get for example the street_number :

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

You can get the desired components iterating over the address_components (I'm retrieving street_number in this example):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM