仅针对一个国家/地区过滤 Google 个地点 API

Filter Google Places API for only one country

按照找到的指南进行操作 https://developers.google.com/maps/documentation/javascript/places-autocomplete#places_searchbox 我正在尝试过滤我的搜索框以仅显示针对英国的建议。

我有代码:

<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 方法。

var options = {
  types: []
};

var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input, options);
// This method.
searchBox.setComponentRestrictions({'country': ['gb']});

最后切换到

function initAutocomplete() {
        var input = document.getElementById('pac-input');
        var options = {
            types: ['(cities)'],
            componentRestrictions: {country: 'GB'}
            };

        var autocomplete = new google.maps.places.Autocomplete(input, options);
    }

解决了我的问题