使用 google 的自动完成服务仅搜索(和输出)国家 and/or 城市

Use google's autocomplete service to search (and output) only country and/or city

我初始化 google 地方 api 如下:

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

在我的代码中,我 bootstrap 服务如下:

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

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

autocomplete.getPlacePredictions('London');

我希望查询仅 return 一组与该查询匹配的城市,但它 return 是伦敦地址列表。

我怎样才能 return 只有匹配该查询的城市结果?

无法将 types 属性 添加到地图 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

希望对您有所帮助!