设置setComponentRestrictions
值有任何限制吗?因为在设置动态值时它不起作用。
方案1(工作正常)
在这种情况下,我对县值进行了硬编码以仅搜索该国家/地区中的特定城市,因此当我使用硬编码值时可以很好地工作。
var input = document.getElementById('searchCity');
var options = { types: ['(cities)'],componentRestrictions: {country: 'us' }};
var autoComplete = new google.maps.places.Autocomplete(cityInput,options);`
方案2(无效)在这里,我有另一个文本字段,我正在使用该字段使用autcomplete查找国家/地区并将short_code值存储在shortNameCountry Id中,但是当我传递动态值时,这不起作用。
var input = document.getElementById('searchCity');
var countryOpt = $("#shortNameCountry").val().toLowerCase();
var options = {types: ['(cities)'], componentRestrictions: {country: countryOpt }};
var autoComplete = new google.maps.places.Autocomplete(input,options);
(我已经添加了自己的方案。但是我不知道stackoverflow会继续要求我添加更多详细信息。我只是在写这些行来解决该警报。)请帮我解决这个问题。
最佳答案
当前,您的代码使用componentRestrictions
属性,该属性将在您创建自动完成时具有输入的值。
要更改此属性,必须在输入值更改时调用setComponentRestrictions
方法。
function initialize() {
var iso = ['AD','AE','AF','AG','AI','AL','AM','AO','AQ','AR','AS','AT','AU','AW','AX','AZ','BA','BB','BD','BE','BF','BG','BH','BI','BJ','BL','BM','BN','BO','BQ','BR','BS','BT','BV','BW','BY','BZ','CA','CC','CD','CF','CG','CH','CI','CK','CL','CM','CN','CO','CR','CU','CV','CW','CX','CY','CZ','DE','DJ','DK','DM','DO','DZ','EC','EE','EG','EH','ER','ES','ET','FI','FJ','FK','FM','FO','FR','GA','GB','GD','GE','GF','GG','GH','GI','GL','GM','GN','GP','GQ','GR','GS','GT','GU','GW','GY','HK','HM','HN','HR','HT','HU','ID','IE','IL','IM','IN','IO','IQ','IR','IS','IT','JE','JM','JO','JP','KE','KG','KH','KI','KM','KN','KP','KR','KW','KY','KZ','LA','LB','LC','LI','LK','LR','LS','LT','LU','LV','LY','MA','MC','MD','ME','MF','MG','MH','MK','ML','MM','MN','MO','MP','MQ','MR','MS','MT','MU','MV','MW','MX','MY','MZ','NA','NC','NE','NF','NG','NI','NL','NO','NP','NR','NU','NZ','OM','PA','PE','PF','PG','PH','PK','PL','PM','PN','PR','PS','PT','PW','PY','QA','RE','RO','RS','RU','RW','SA','SB','SC','SD','SE','SG','SH','SI','SJ','SK','SL','SM','SN','SO','SR','SS','ST','SV','SX','SY','SZ','TC','TD','TF','TG','TH','TJ','TK','TL','TM','TN','TO','TR','TT','TV','TW','TZ','UA','UG','UM','US','UY','UZ','VA','VC','VE','VG','VI','VN','VU','WF','WS','YE','YT','ZA','ZM','ZW'];
goo = google.maps,
input = document.getElementById('searchCity'),
country = document.getElementById('shortNameCountry'),
options = {types: ['(cities)']},
autoComplete = new google.maps.places.Autocomplete(input,options);
goo.event.addDomListener(country,'input',function(){
var val=this.value.trim().toUpperCase();
if(iso.indexOf(val)>-1){
this.style.background='white';
input.value=' ';
autoComplete
.setComponentRestrictions({country:val});
}
else{
this.style.background='red';
}
});
goo.event.trigger(country,'input');
}
google.maps.event.addDomListener(window, 'load', initialize);
<input id="searchCity"/>
<input id="shortNameCountry" size="2" maxlength="2" value="de"/>
<script src="https://maps.googleapis.com/maps/api/js?v=3&libraries=places"></script>