Google maps API - 仅通过邮政编码进行检索

时间:2016-09-08 10:47:45

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

我正在尝试对Google Maps Autocomplete API进行一些限制。

我希望它只检索和自动填写邮政​​编码,没有别的,甚至不是国家。但我正在努力过滤它。我对这个过程的文件感到困惑。

如何解决此问题?

以下是代码:

HTML

<form role="form">
     <input type="text" class="form-control" id="locality" name="locality" placeholder="Stadt oder PLZ" />
</form>

的Javascript

var localityInput = document.getElementById('locality');
var localityOptions = {
  types: ['(regions)'], #Retrieve postal code only
  componentRestrictions: {country: 'ch'}
};
autocomplete = new google.maps.places.Autocomplete(localityInput, localityOptions);

更新1

我在尝试链接2个不同的javascript代码,但我不知道如何做到这一点。

HTML

<form role="form">
     <input type="text" class="form-control" id="locality" name="locality" placeholder="Stadt oder PLZ" />
     <div id="postal_code"></div>
</form>

的Javascript

var localityInput = document.getElementById('locality');
var localityOptions = {
  types: ['address'],
  componentRestrictions: {country: 'ch'}
};
autocomplete = new google.maps.places.Autocomplete(localityInput, localityOptions);

  google.maps.event.addListener(autocomplete, function() {
    var place = autocomplete.getPlace();
    for (var i = 0; i < place.address_components.length; i++) {
      for (var j = 0; j < place.address_components[i].types.length; j++) {
        if (place.address_components[i].types[j] == "postal_code") {
          document.getElementById('postal_code').innerHTML = place.address_components[i].long_name;
        }
      }
    }
  })

1 个答案:

答案 0 :(得分:0)

找到了一种方法,这要归功于 stackoverflow.com/questions/34487077/ 这是最终的代码。

仅当邮政编码在搜索栏中时才有效。

<form role="form">
     <input type="text" class="form-control" id="locality" name="locality" placeholder="Stadt oder PLZ" />
     <div id="postal_code"></div>
</form

<script>
var localityInput = document.getElementById('locality');
var localityOptions = {
  types: ['(regions)'],
  componentRestrictions: {country: 'ch'}
};
autocomplete = new google.maps.places.Autocomplete(localityInput, localityOptions);
  google.maps.event.addListener(autocomplete, 'place_changed', function() {
    var place = autocomplete.getPlace();
    for (var i = 0; i < place.address_components.length; i++) {
      for (var j = 0; j < place.address_components[i].types.length; j++) {
        if (place.address_components[i].types[j] == "postal_code") {
          document.getElementById('postal_code').innerHTML = place.address_components[i].long_name;

        }
      }
    }
  })
google.maps.event.addDomListener(window, "load", initialize);
</script>