Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get postal code with autocomplete service from google maps api v3

I'm using the autocompleteservice from google maps api V3 to make a custom autocomplete input. I basically call this function to retrieve cities suggestions.

function getPlaces(st){
    gService.getQueryPredictions({input:st,types:['geocode']},function(predictions,status)      {
        if(status != google.maps.places.PlacesServiceStatus.OK) return false;
        for(var i = 0, prediction; prediction = predictions[i]; i++){
            console.log(prediction);
        }
        return predictions;
    });
}

This is working great, but i want to get the zip code associated to cities. Like the V2 api did, see this example.

I tried to change the types option to cities, but the result is the same. Any idea how to do that?

like image 930
loicb Avatar asked Dec 05 '12 20:12

loicb


People also ask

How do I get a postcode from Google Maps?

Open a contact or an organization with a postal address. Beside the postal address, click on the map icon. The postal address will automatically open on Google Maps.

Is Google Maps Autocomplete API free?

The autocomplete request is available at no charge, and the subsequent Place Details call gets charged based on regular Place Details pricing. A Place Details request generates Data SKUs (Basic, Contact, and/or Atmosphere) – depending on the fields that are specified in the request.


1 Answers

Check this code snippet:

    var geocoder;
var map;
function initialize() {  
  var input = document.getElementById('id_address');
  var options = {
    types: ['address'],
    componentRestrictions: {
      country: 'in'
    }
  };

  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)
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDxcRPSsACIjdvMWRcfJBMzp4pKQXPJjj0&libraries=places"></script>
<input id="id_address" type="text" value="" />
<div id="postal_code"></div>
like image 67
Varun Sharma Avatar answered Nov 06 '22 22:11

Varun Sharma