Google Maps Geocoder: Return postal_code

寵の児 提交于 2020-01-04 05:16:14

问题


I'm using Jquery UI to autocomplete search for an address using Google Maps Geocoder, and when an address is selected it returns the geocode information. Here is the snippet:

$('#address-dropdown').autocomplete({
  //Use geocoder to fetch lat+long values from an address input using google maps API
  source: function(request, response) {
    geocoder.geocode( {'address': request.term }, function(results, status) {
      response($.map(results, function(item) {
        return {
          label: item.formatted_address,
          value: item.formatted_address,
          location: item.geometry.location,
          latitude: item.geometry.location.lat(),
          longitude: item.geometry.location.lng()
        }
      }));
    })
  },

I need to ability to return the uses "postal_code" to check if they live within an allowable area. Here is an example output: http://maps.googleapis.com/maps/api/geocode/json?address=1601+Main+St+Eaton+Rapids+MI+48864&sensor=false

How could I target the postal_code information?


回答1:


Look at my example: http://jsfiddle.net/nEKMK/

o is your object.

if (o.results[0].address_components) {
    for (var i in o.results[0].address_components) {
        if (typeof(o.results[0].address_components[i]) === "object" && o.results[0].address_components[i].types[0] == "postal_code") {
            var result = o.results[0].address_components[i].long_name;
        }
    }
}
if (!result) {
    alert("Error, there is no postal code");
} else {
   alert(result);
}


来源:https://stackoverflow.com/questions/8380511/google-maps-geocoder-return-postal-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!