问题
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