google map api autosuggest:从另一个地址动态更改限制

use*_*206 1 javascript google-maps-api-3

我正在使用谷歌地图api v3进行gmap automcomplete.请问如何动态地从另一个地址设置有偏见的国家和城市?

这是我现有的代码:

<script>
    function initialize() {
        var input_location = document.getElementById('id_location');
        var options_location = {
            componentRestrictions: {country: 'fr'}
        };
        var autocomplete_location = new google.maps.places.Autocomplete(input_location);

    }
    google.maps.event.addDomListener(window, 'load', initialize);
</script>
Run Code Online (Sandbox Code Playgroud)

从上面你可以看到我将搜索限制在法国.

但是我想根据另一个地址改变这个国家呢?

例如:日内瓦国际机场,瑞士Grand-Saconnex

非常感谢


编辑:

还有一个问题(但是这个问题与我上面提到的问题密切相关,所以我不问新的问题.)如果地址不同怎么办?例如:a1:巴西a2:日内瓦国际机场,瑞士Grand-Saconnex

从address_components,我不应该总是提取第二个元素作为国家.

EDIT2:

问题解决了.我写了一个for循环来检查'country'是否在类型中以获取国家/地区代码:

geocoder.geocode({address: address}, function (result, status) {
                if (status === 'OK' && result.length > 0) {
                    var i = 0;
                    len = result[0].address_components.length;
                    for (; i < len; i++){
                        if (result[0].address_components[i].types.indexOf('country') >= 0) {
                            c_code = result[0].address_components[i].short_name;
                        }
                    }

                    var options = {
                        componentRestrictions: {country: c_code }
                    };

                    var input_location = document.getElementById('id_location');
                    var autocomplete_location = new google.maps.places.Autocomplete(input_location, options);

                }
            })
Run Code Online (Sandbox Code Playgroud)

MrU*_*own 10

使用该类的setComponentRestrictions()方法Autocomplete.请参阅文档.

var country = 'fr';
var autocomplete_location = new google.maps.places.Autocomplete(input_location);

autocomplete_location.setComponentRestrictions({'country': country});
Run Code Online (Sandbox Code Playgroud)