我有一个用户输入其位置的输入。从这个位置,我想获取城市,州和邮政编码并将这些信息输入另一个输入(城市,州和邮政编码的输入),因此用户不需要手动填写这些信息。
我找到了一个我想要实现的目标的例子here并尝试根据我的需要对其进行修改。
所以我走了:
var placeSearch, autocomplete_origin_address, autocomplete_destination_address;
var componentForm_origin = {
user_origin_city: 'user_origin_city',
user_origin_state: 'user_origin_state',
user_origin_zip: 'user_origin_zip'
};
function initAutocomplete() {
console.log('in "initAutocomplete"');
autocomplete_origin_address = new google.maps.places.Autocomplete(
document.getElementById('user_origin_address'),
types: ['geocode']}
);
autocomplete_origin_address.addListener("place_changed",
fillInAddress(autocomplete_origin_address,
"user_origin_address",
"user_origin_city",
"user_origin_state",
"user_origin_zip"));
}
function fillInAddress(autocomplete_resource, address, city, state, zip) {
console.log("! !x");
// Get the place details from the autocomplete object.
var place = autocomplete_resource.getPlace();
// origin fields to populate with the selected address
var fetched_street_number = fetchAddressDetails(place, "street_number", "long_name");
var fetched_address = fetchAddressDetails(place, "route", "long_name");
$("#"+address).val(fetched_street_number + " " + address);
var fetched_city = fetchAddressDetails(place, "locality", "long_name");
$("#"+city).val(fetched_city);
var fetched_state = fetchAddressDetails(place, "administrative_area_level_1", "short_name");
$("#"+state).val(fetched_state);
var fetched_zip = fetchAddressDetails(place, "postal_code", "long_name");
$("#"+zip).val(fetched_zip);
}
function fetchAddressDetails(autocomplete_place, detail_type, name_type){
console.log("in fetchAddressDetails");
var item = $.grep(autocomplete_place.address_components,
function(e){ return e.types[0] == detail_type; });
var item_data = item[0][name_type];
console.log("item_data: "+item_data);
return item_data;
}
initAutocomplete();
但是当我加载页面时,我收到此错误:
in "initAutocomplete"
! !x
in fetchAddressDetails
Uncaught TypeError: Cannot read property 'address_components' of undefined
我正在尝试谷歌这个问题,但无法摆脱它并使代码工作。 我一般都在尝试 - 我在页面上有4个输入,用户输入地址。 所以我想 - 当输入这4个输入中的每个输入的地址时 - 使用谷歌自动完成功能,获取地址并将城市/州/邮政信息放入相应的输入。
你能告诉我,为什么它目前还没有取得任何东西?
提前谢谢。
答案 0 :(得分:0)
也许只是一个错字,但是有一个语法错误可能导致问题......
types: ['geocode']} // <~~ missing it's opening curly brace..!
应该阅读......
{types: ['geocode']}