Amit Kumar
Amit Kumar

Reputation: 1772

Get only city name in Autocomplete suggestions using Google Places API

I am using the below code to get the city suggestion but it's giving me the city + state + country, but I need only city name

<html>
  <head>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
    <script>
        var autocomplete;
        function initialize() {
        autocomplete = new google.maps.places.Autocomplete(document.getElementById('autocomplete'), { types: ['(cities)'], componentRestrictions : { country: 'in' }});

        }
    </script>
  </head>
  <body onload="initialize()">
    <div id="locationField">
      <input id="autocomplete" placeholder="Enter your address" onFocus="geolocate()" type="text"></input>
    </div>
  </body>
</html>

Any suggestion?

Upvotes: 3

Views: 3886

Answers (1)

AlexB
AlexB

Reputation: 7416

You can't remove these informations, however, you can mask them using CSS.

Please refer to this link.

To quote the official documentation, here are the classes used by the components of the Autocomplete. enter image description here

So I suggest you to use CSS to hide the part(s) you don't want to display.
In your case, you can use :

.pac-item-query + span
{
    display: none
}

This will hide the next adjacent <span> to the <span> whose class is pac-item-query (which contains the suggested name of the city only), and so, only let the city displayed.
Thus, the state / country is masked, as you required.

Be careful, the + pseudo-selector is not supported by all browsers, including IE6. Please check your browser requirements before using it.

Upvotes: 4

Related Questions