【问题标题】:Restrict google autocomplete output to city only将谷歌自动完成输出仅限于城市
【发布时间】:2018-12-08 06:43:52
【问题描述】:

我有以下代码使用 google 自动完成 api 查找来自给定国家/地区的城市:

<script src="https://maps.googleapis.com/maps/api/js?key=KEY&sensor=false&libraries=places&region=uk" type="text/javascript"></script>

     function initialize() {
       var input = document.getElementById('searchTextField');
       var options = {
         types: ['(cities)'],
         componentRestrictions: { country: "uk" }
     };
       var autocomplete = new google.maps.places.Autocomplete(input, options);
     }
 google.maps.event.addDomListener(window, 'load', initialize);

我在脚本 src 中添加了区域,以免在输出中包含国家/地区。
例如,如果我输入 Lo,我只会得到 London 而不是 London, UK

但是,由于我从下拉列表中获取国家及其 ISO 代码,因此我需要能够更改 google api URL 中的 componentRestrictions 和区域。 知道怎么做吗?我知道我可以从下拉列表中选择国家,如下所示:

var country= $('#CountryDropdown');

如何将 var country 传递给 componentRestrictions 和 region?

【问题讨论】:

    标签: javascript autocomplete google-api


    【解决方案1】:

    我有同样的问题,我通过这个解决了。 希望这会帮助你。

    <script src="https://maps.googleapis.com/maps/api/js?key=Yourkey&v=3.exp&libraries=places"></script>
    
    function initialize() {
    
        var input = document.getElementById('FullAddress');
        var options = {
            types: ['address'],
            componentRestrictions: { country: 'uk' }
        };
        autocomplete = new google.maps.places.Autocomplete(input, options);
    
        google.maps.event.addListener(autocomplete, 'place_changed', function () {
            // Get the place details from the autocomplete object.
            var place = autocomplete.getPlace();
            for (var component in componentForm) {
                document.getElementById(component).value = '';
                // document.getElementById(component).disabled = false;
            }
            $("#Latitude").val(place.geometry.location.lat());
            $("#Longitude").val(place.geometry.location.lng());
    
            // Get each component of the address from the place details
            // and fill the corresponding field on the form.
            for (var i = 0; i < place.address_components.length; i++) {
                var addressType = place.address_components[i].types[0];
                if (componentForm[addressType]) {
                    var val = place.address_components[i][componentForm[addressType]];
                    document.getElementById(addressType).value = val;
                }
            }
        });
    }
    

    【讨论】:

    • 我试过了,但它不起作用。当我调试它时,我可以看到它没有输入代码:google.maps.event.addListener(autocomplete, 'place_changed', function () {... 知道为什么吗?
    猜你喜欢
    • 2012-12-28
    • 2012-01-07
    • 2018-03-24
    • 2017-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-26
    • 1970-01-01
    相关资源
    最近更新 更多