首页 > 解决方案 > 如何使用 Maps API 获取澳大利亚的郊区列表

问题描述

在我的项目中,我希望用户选择一个澳大利亚郊区。当用户键入 Suburb 时,该表单具有自动建议字段,它需要建议与查询匹配的郊区。以下屏幕截图显示了我确切需要的内容。

有人可以知道我应该使用什么 Google Maps API 吗?我已经浏览了谷歌文档,但我还没有找到。提前致谢。

截屏

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

解决方案


您可以根据需要使用自动完成types选项。(regions)(cities)

您还可以使用componentRestrictions将结果限制在特定地区或国家,在您的情况下为澳大利亚。

function initialize() {

  var ac = new google.maps.places.Autocomplete(
    (document.getElementById('autocomplete')), {
      types: ['(cities)'],
      componentRestrictions: {
        country: 'AU'
      }
    });

  ac.addListener('place_changed', function() {

    var place = ac.getPlace();

    if (!place.geometry) {
      // User entered the name of a Place that was not suggested and
      // pressed the Enter key, or the Place Details request failed.
      window.alert("No details available for input: '" + place.name + "'");
      return;
    }

    // Alert the selected place
    window.alert("You selected: '" + place.formatted_address + "'");
  });
}
#autocomplete {
  width: 300px;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&callback=initialize" async defer></script>
<input id="autocomplete" placeholder="Enter your address" type="text"></input>

请注意,您需要在 API 调用中加载地点库:

<script src="https://maps.googleapis.com/maps/api/js?libraries=places&callback=initialize" async defer></script>


推荐阅读