首页 > 解决方案 > Google 地方信息自动完成 - 类型:地理编码、地址、机构 - 无法正常工作

问题描述

我正在尝试在 google 地方自动完成中设置类型,这让我抓狂!

我希望我的用户能够通过输入他们正在寻找的地址或机构来过滤那里的搜索,但由于某种原因它无法正常工作。

我正在使用的代码:

<script defer src="https://maps.googleapis.com/maps/api/js?libraries=places&key=[my_api_key]"></script>
<script>
    var searchInputStart = 'start_address';
    start_address = new google.maps.places.Autocomplete((document.getElementById(searchInputStart)), {
        types: ['geocode'],
        types: ['address'],
        types: ['establishment']
    });
    google.maps.event.addListener(start_address, 'place_changed', function () {
        var place_start = start_address.getPlace();
        document.getElementById('loc_lat_start').value = place_start.geometry.location.lat();
        document.getElementById('loc_long_start').value = place_start.geometry.location.lng();
        //get_directions to address
        set_route();
    });
</script>

如果我取出 --> types: [address] --> 它显示正确的机构,但不是地址。

如果我取出 --> types: [establishement] --> 它显示地址正确,但不显示设施。

我的用户如何通过输入地址或机构正确过滤地点?

任何人都可以帮助我吗?我究竟做错了什么?

谢谢你。

标签: google-mapsgoogle-maps-api-3google-places-apigoogleplacesautocomplete

解决方案


根据 Google Maps API 文档,您只能在适当的位置设置一种类型的自动完成选项。

types Array<string>:要返回的预测类型。有关受支持类型的列表,请参阅开发人员指南。如果未指定任何内容,则返回所有类型。通常只允许使用一种类型。例外情况是您可以安全地混合使用 'geocode' 和 'establishment' 类型,但请注意,这与不指定类型具有相同的效果。

来源:https ://developers.google.com/maps/documentation/javascript/reference/places-widget#AutocompleteOptions

这意味着您可以使用

start_address = new google.maps.places.Autocomplete(
    document.getElementById(searchInputStart), 
    {
        types: ['address']
    }
);

或者

start_address = new google.maps.places.Autocomplete(
    document.getElementById(searchInputStart), 
    {
        types: ['geocode', 'establishment']
    }
);

但并非所有这些都在同一个选项对象中。

希望我的回答能澄清你的疑惑。


推荐阅读