【问题标题】:Use google's autocomplete service to search (and output) only country and/or city使用谷歌的自动完成服务仅搜索(和输出)国家和/或城市
【发布时间】:2019-12-03 09:05:24
【问题描述】:

我初始化 google places api 如下:

<script
      type="text/javascript"
      src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places&types=cities"
    ></script>

在我的代码中,我按如下方式引导服务:

const autocomplete = new window.google.maps.places.AutocompleteService();

autocomplete.getPlacePredictions({ input }, predictions => {
 console.log(predictions);
});

autocomplete.getPlacePredictions('London');

我希望查询只返回一组与该查询匹配的城市,但它会返回伦敦地址列表。

如何让它只返回与该查询匹配的城市结果?

【问题讨论】:

    标签: javascript google-maps google-places-api


    【解决方案1】:

    types 属性不能添加到 Maps API 脚本本身。您需要将其添加到您对AutocompleteService.getPlacePredictions 的请求中,如下所示:

    autocomplete.getPlacePredictions({ input: 'London', types : ['(cities)'] }, predictions => {
        console.log(predictions);
    });
    

    Maps JS API 脚本(不含types):

    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places"></script>
    

    输出:

    London, UK
    London, ON, Canada
    London, KY, USA
    Londonderry, UK
    London, OH, USA
    

    参考以下资源:
    AutocompletionRequest interface reference
    Autocomplete for Addresses and Search Terms

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-07
      • 2020-08-14
      • 2012-12-28
      • 2018-12-08
      • 1970-01-01
      • 2013-11-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多