我在这个网站上找到了从邮政编码获取州名的代码,但我还需要获取城市名称。
这是我获取状态的代码:(注意我也使用 jQuery)
var geocoder = new google.maps.Geocoder();
$('.zip').bind('change focusout', function () {
var $this = $(this);
if ($this.val().length == 5) {
geocoder.geocode({ 'address': $this.val() }, function (result, status) {
var state = "N/A";
//start loop to get state from zip
for (var component in result[0]['address_components']) {
for (var i in result[0]['address_components'][component]['types']) {
if (result[0]['address_components'][component]['types'][i] == "administrative_area_level_1") {
state = result[0]['address_components'][component]['short_name'];
// do stuff with the state here!
$this.closest('tr').find('select').val(state);
}
}
}
});
}
});
原文由 boruchsiper 发布,翻译遵循 CC BY-SA 4.0 许可协议
只需添加
result[0]['address_components'][1]['long_name']
所以它会是