我在这个网站上找到了从邮政编码中获取状态的代码,但我还需要获取城市名称.
@H_301_8@解决方法
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); } } } }); } });
只需添加结果[0] [‘address_components’] [1] [‘long_name’]
所以它会
var geocoder = new google.maps.Geocoder(); $('.zip').bind('change focusout',function () { var $this = $(this); if ($this.val().length == 5) { geocoder.geocode({ 'address': $this.val() },status) { var state = "N/A"; var city = "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); // get city name city = result[0]['address_components'][1]['long_name']; // Insert city name into some input Box $this.closest('tr').find('.city').val(city); } } } }); } });