Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
655 views
in Technique[技术] by (71.8m points)

javascript - How do I get the postal code from google map's autocomplete api

So my issue is that the results are spitting out as:

1980 Mission Street, San Francisco, CA, United States

...but I need it to give me the zipcode because when I put it back into google's Geocoder, for some reason it doesn't register the location.

// This is the code I have just the autocomplete input field

var input = document.getElementById('id_address');
var options = {
  types: ['address'],
  componentRestrictions: {country:'us'}
};
autocomplete = new google.maps.places.Autocomplete(input, options);

// This is how I'm using the geocoder

window.onload = function initMap() {
            console.log("{{ task.address }}");
            console.log("{{ location }}");
            var address = "{{ location }}";

            geocoder = new google.maps.Geocoder();

            geocoder.geocode({ 'address': address }, function(results, status) {
                <!-- console.log(address); -->
              if (status == google.maps.GeocoderStatus.OK) {
                var map = new google.maps.Map(document.getElementById('map'), {
                    center: results[0].geometry.location,
                    zoom: 12,
                  });
                var marker = new google.maps.Marker({
                    map: map,
                    position: results[0].geometry.location,
                  });
              }


            });

        }

I have a working solution, but the user will have to input each piece of the address separately. I'm trying to change it so they can just fill out one input field and then I can spit that address into the gecoder.geocode().

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The result returned by the autocomplete contains an address_components array, one entry of which has the type 'postal_code', which for your sample address ("1980 Mission Street, San Francisco, CA, United States"), contains 94103.

Note: a city, county or state usually has more than one postal code, the only way to get a unique one would be to reverse geocode the returned coordinates, whether that is adequate will depend on the use.

proof of concept fiddle

function initialize() {
  var input = document.getElementById('id_address');
  var options = {
    types: ['address'],
    componentRestrictions: {
      country: 'us'
    }
  };
  autocomplete = new google.maps.places.Autocomplete(input, options);
  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);
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<input id="id_address" type="text" size="100" value="1980 Mission Street, San Francisco, CA, United States" />zip code:
<div id="postal_code"></div>
<div id="map_canvas"></div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...