如何搜索邮政编码和城市Google Maps

时间:2018-08-16 00:17:18

标签: javascript html google-maps maps

嗨,我有一个代码,只能搜索澳大利亚的城市。

我如何也可以搜索邮政编码?

请参阅我的代码:

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>

1 个答案:

答案 0 :(得分:0)

类型中使用regions代替cities导致cities限于localityadministrative_area_level_3,其中regions包括postal_code

  1. 位置
  2. 次地区性
  3. 国家
  4. administrative_area_level_1
  5. administrative_area_level_2

检查来源:(https://developers.google.com/places/web-service/autocomplete#place_types

使用下面的更新代码

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

还要检查更新的代码段。

function initialize() {

  var ac = new google.maps.places.Autocomplete(
    (document.getElementById('autocomplete')), {
      types: ['(regions)'],
      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>