Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Places JavaScript Autocomplete: can I remove the country from the place name?

I have the following jQuery code which works well with getting the city list for the selected country.

var city;   var place;

$('#city').on('focus',function(){
    input = this, options = {
        types: ['(cities)'],
        componentRestrictions: {
            country: $('#country option:selected').val()
            }
    };
    city = new google.maps.places.Autocomplete(input, options);
    google.maps.event.addListener(city, 'place_changed', function() {
        place = city.getPlace();
        $(input).val(place.address_components[0].long_name);
    })
})

Basically, once the person selects the place, it replaces the value in the input box with the "city" value without the country.

It looks a little stupid having City, Country in the dropdown menu when the user has already selected a country, so does anybody know if it is possible to display JUST the city name if you have defined a componentRestrictions value restricting the results to a country?

I find my current method of setting it once the selection has been made to be a bit... rubbish really...

like image 494
Andrew Willis Avatar asked May 16 '12 21:05

Andrew Willis


1 Answers

When invoking Google API, specify attribute "region":

<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false&key=your_key&language=fr&region=FR"></script>

Then, when you create an Autocomplete object, specify the country in the componentRestriction attribute, so that it reflects the region you specified:


    new google.maps.places.Autocomplete(
        $("#my-input-field").get(0),
        {
            componentRestrictions: {country: "fr"},
            types: ["(regions)"]
        }
    );

like image 74
Marek Stanley Avatar answered Sep 20 '22 12:09

Marek Stanley