Javascript 筛选Google仅为一个国家/地区放置API
根据指南,我试图过滤我的搜索框,只显示对英国的建议 我有密码:Javascript 筛选Google仅为一个国家/地区放置API,javascript,google-places-api,Javascript,Google Places Api,根据指南,我试图过滤我的搜索框,只显示对英国的建议 我有密码: <script src="https://maps.googleapis.com/maps/api/js?key=XXXXXXX&libraries=places&callback=initialize&v=3" async defer></script> <script> function initialize() { set
<script src="https://maps.googleapis.com/maps/api/js?key=XXXXXXX&libraries=places&callback=initialize&v=3"
async defer></script>
<script>
function initialize() {
setTimeout(function() {
initMap();
initAutocomplete();
}, 4000);
}
function initAutocomplete() {
var options = {
types: [],
componentRestrictions: {country: 'GB' }
};
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input, options);
}
</script>
它的工作原理是搜索框得到初始化,并且可用,但是它不只是过滤到英国的位置。该框将显示世界各地的位置建议
使用GB或GB会得到相同的结果
请尝试使用小写的国家/地区:
<script src="https://maps.googleapis.com/maps/api/js?key=XXXXXXX&libraries=places&callback=initialize&v=3"
async defer></script>
<script>
document.onload = function initialize() {
initMap();
initAutocomplete();
}
function initAutocomplete() {
var options = {
types: [],
componentRestrictions: {country: 'gb' }
};
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input, options);
}
</script>
也许可以尝试setComponentRestrictions方法
最后切换到
function initAutocomplete() {
var input = document.getElementById('pac-input');
var options = {
types: ['(cities)'],
componentRestrictions: {country: 'GB'}
};
var autocomplete = new google.maps.places.Autocomplete(input, options);
}
修正了我的问题他们的例子说小写的country:componentRestrictions:{country:'fr'}。尝试将其小写?没有骰子相同的问题似乎有点奇怪,您使用的是超时调用;这就是PlacesAPI建议准备好安装调用的方式吗?尽管等待了4秒,但可能无法完全加载,这可能会导致一些问题。你能改为用document.onload来写它以确保JS被正确加载吗?这给了我[Error]InvalidValueError:initialize不是一个函数Cg JS:96:131匿名函数JS:162加载JS:21匿名函数JS:161全局代码JS:162
function initAutocomplete() {
var input = document.getElementById('pac-input');
var options = {
types: ['(cities)'],
componentRestrictions: {country: 'GB'}
};
var autocomplete = new google.maps.places.Autocomplete(input, options);
}