Naqi
Naqi

Reputation: 252

How can I restrict the Google Maps Places Library's Autocomplete to suggestions of only one city's places?

I am currently using the given code, but this only restricts suggestions to one country. I have seen one implementation but its using jQuery and I want to do it without using jQuery.

var input = document.getElementById('searchTextField');
var options = {
    //types: ['(cities)'],
    componentRestrictions: { country: 'pk' }
};
var autocomplete = new google.maps.places.Autocomplete( input, options );

Upvotes: 9

Views: 21494

Answers (3)

Paul Beck
Paul Beck

Reputation: 2685

For multiple country restrictions you can use

var options = {
    types: ['(cities)'],
    componentRestrictions: {
        country: ['de','at','ch']
    }
};

Upvotes: 1

Rommel Paras
Rommel Paras

Reputation: 325

I found awesome examples of restricting or limiting search results by country using the Autocomplete class, i.e. there is a method called setComponentRestrictions which allows you to set the country (property), found here -https://developers.google.com/maps/documentation/javascript/reference#ComponentRestrictions

Please check out https://code.google.com/p/gmaps-samples-v3/source/browse/trunk/places/2012-may-hangout/autocomplete.html?r=290 for examples.

Upvotes: 2

Sean Mickey
Sean Mickey

Reputation: 7716

Try adding a bounds property to the options object you are passing to the Autocomplete constructor, as shown in this code:

var southWest = new google.maps.LatLng( 25.341233, 68.289986 );
var northEast = new google.maps.LatLng( 25.450715, 68.428345 );
var hyderabadBounds = new google.maps.LatLngBounds( southWest, northEast );

var options = {
    bounds: hyderabadBounds,
    types:  ['establishment [or whatever fits your usage]'],
    componentRestrictions: { country: 'pk' }
};

If you want the Autocomplete bounds to be driven by the current viewport of the map, you can bind the bounds of the map to the Autocomplete this way:

autocomplete.bindTo('bounds', map);

Or, if it works better in your application, you also have the option to set the bounds explicitly whenever necessary:

autocomplete.setBounds( someOtherBounds );

This may mean that you create a default city, as I did with Hyberabad in the example above. Or that you allow your users to select from a list of cities to start and then set the map viewport to the selected city. The Autocomplete will suggest city names if you start out with just the componentRestrictions of country 'PK' as you are already doing. You will know what works best for your application.

Finally, this does not truly and completely restrict the Autocomplete to just the city, but it will achieve the result you wish as closely as currently possible.

Upvotes: 23

Related Questions