Rajat Gupta
Rajat Gupta

Reputation: 26587

City's name or id of the chosen city using Google Places autocomplete API

I want to use Google Places autocomplete API to search for locations through text search. Is it possible to a get the city name or the cityId of the chosen city in the autocomplete box, using the places autocomplete API ?

Upvotes: 1

Views: 2589

Answers (1)

Dr.Molle
Dr.Molle

Reputation: 117314

You may access the address_components of the current place via autocompleteInstance.getPlace()

The component where the types- property (it's an array) contains the values political and locality usually is the city.

Example:

google.maps.event.addListener(autocomplete, 'place_changed', function() {
  var components=this.getPlace().address_components,city='n/a';
      if(components){
        for(var c=0;c<components.length;++c){
        console.log(components[c].types.join('|'))
          if(components[c].types.indexOf('locality')>-1
              &&
             components[c].types.indexOf('political')>-1
            ){
            city=components[c].long_name;
            break;
          }
        }
      }
    alert(city)
  });

Upvotes: 1

Related Questions