问题
If I pass my GeoCoding call only a city and state it fails to return the postal code. Any idea why?
Here is my call:
var test = 'New York, NY';
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': test }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var lat = results[0].geometry.location.lat();
var lng = results[0].geometry.location.lng();
var result=results[0].address_components;
//console.log(result);
var postal = null;
var city = null;
var state = null;
var country = null;
for(var i=0;i<result.length;++i){
if(result[i].types[0]=="postal_code"){
postal = result[i].long_name;
}
if(result[i].types[0]=="administrative_area_level_1"){
state = result[i].long_name;
}
if(result[i].types[0]=="locality"){
city = result[i].long_name;
}
if(result[i].types[0]=="country"){
country = result[i].long_name;
}
}
alert("POSTAL: " + postal);
alert("STATE: " + state);
alert("CITY: " + city);
alert("COUNTRY: " + country);
}
回答1:
If you really need a zip code, you can throw the request back to the reverse geocoder, that should give you a zip code somewhat representative of the city:
if (!postal) {
geocoder.geocode({ 'location': results[0].geometry.location }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var result=results[0].address_components;
for(var i=0;i<result.length;++i){
if(result[i].types[0]=="postal_code"){
postal = result[i].long_name;
}
}
alert("POSTAL: " + postal);
}
});
} else alert("POSTAL: " + postal);
example
来源:https://stackoverflow.com/questions/13993474/why-does-google-geocoding-only-sometimes-return-the-postal-code