我正在尝试将自动填充功能限制在特定国家/地区,即美国。我怎样才能做到这一点?我通过将变量选项作为参数传递给初始化函数来尝试以下内容:
<script>
var autocomplete = {};
var autocompletesWraps = ['test', 'test2'];
var test_form = { street_number: 'short_name', route: 'long_name', locality: 'long_name', administrative_area_level_1: 'short_name', country: 'long_name', postal_code: 'short_name' };
var test2_form = { street_number: 'short_name', route: 'long_name', locality: 'long_name', administrative_area_level_1: 'short_name', country: 'long_name', postal_code: 'short_name' };
function initialize() {
var options = {
types: ['(cities)'],
componentRestrictions: {country: "us"}
};
$.each(autocompletesWraps, function(index, name) {
if($('#'+name).length == 0) {
return;
}
autocomplete[name] = new google.maps.places.Autocomplete($('#'+name+' .autocomplete')[0], { types: ['geocode'] }, options);
google.maps.event.addListener(autocomplete[name], 'place_changed', function() {
var place = autocomplete[name].getPlace();
var form = eval(name+'_form');
for (var component in form) {
$('#'+name+' .'+component).val('');
$('#'+name+' .'+component).attr('disabled', false);
}
for (var i = 0; i < place.address_components.length; i++) {
var addressType = place.address_components[i].types[0];
if (typeof form[addressType] !== 'undefined') {
var val = place.address_components[i][form[addressType]];
$('#'+name+' .'+addressType).val(val);
}
}
});
});
}
</script>
答案 0 :(得分:2)
您未正确传递options
。 Autocomplete
有两个参数,你通过了三个。
具体来说,在这一行:
autocomplete[name] = new google.maps.places.Autocomplete(
$('#'+name+' .autocomplete')[0], { types: ['geocode'] }, options);
您的options
参数未使用,因为您已将{ types: ['geocode'] }
作为选项传递。
所以删除额外的参数:
var options = {
types: ['geocode'], // or '(cities)' if that's what you want?
componentRestrictions: {country: "us"}
};
autocomplete[name] = new google.maps.places.Autocomplete(
$('#'+name+' .autocomplete')[0], options);
答案 1 :(得分:1)
如果您想将Google Address API仅与英国地址集成。请找到以下地址:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places" async defer></script>
<script type="text/javascript>
var autocomplete;
function initialize() {
autocomplete = new google.maps.places.Autocomplete(
(document.getElementById('txtpostcode')),
{ types: ['geocode'] });
autocomplete.setComponentRestrictions(
{'country': ['uk']});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
});
}
</script>