How do I get the postal code from google map's autocomplete api
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>