Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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().

like image 552
Chris Avatar asked Dec 28 '15 02:12

Chris


People also ask

How do I get data from Google Maps Places API?

Go to APIs & Services → Dashboard → Enable APIs & Services at the top and Choose Maps JavaScrip API from the API Library. This will open up the Map JavaScript API page, and Enable it.

How do I use Google Places autocomplete API?

Ensure that the API key(s) used for all Place Autocomplete and Place Details requests within a session belong to the same Cloud Console project. Be sure to pass a unique session token for each new session. Using the same token for more than one session will result in each request being billed individually.

How do I get my city name from places API?

2) Make another web-service call to https://maps.googleapis.com/maps/api/place/details/json?key=API_KEY&placeid=place_id_retrieved_in_step_1. This will return a JSON which contains address_components . Looping through the types to find locality and postal_code can give you the city name and postal code.

What is the postal code in the autocomplete result?

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.

How do I find the postal address on a Google map?

With the Google Maps Lookup tool, you can quickly determine the approximate postal address of any location on the world map. Just drag the red marker anywhere on the Google Map and the address details (including the latitude & longitude) of that place will display in the pop-up window.

Can I use place autocomplete without a map?

Note: You can use Place Autocomplete even without a map. If you do show a map, it must be a Google map. When you display predictions from the Place Autocomplete service without a map, you must include the ' Powered by Google ' logo displayed inline with the search field/results.

How do I use place autocomplete with geocoding?

If Place Autocomplete is accompanied by a map, you can bias location by map viewport. If you expect the user to enter only address information, re-use the original user input in a call to the Geocoding API. If you expect the user to enter queries for a specific place by name or address, use a Find Place request .


1 Answers

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>
like image 85
geocodezip Avatar answered Sep 19 '22 17:09

geocodezip