I'm setting up a custom autocomplete field where I show locations from Google Places and events from my database that match the search query. For this reason, I'm using the Google Places Autocomplete Service to get the query predictions rather than plugging in the Places Autocomplete directly into my textfield.
The problem is I can't figure out how to filter Places Autocomplete suggestions by country using the AutoComplete service.
I've tried:
var service = new google.maps.places.AutocompleteService(null, {
types: ['cities'],
componentRestrictions: {country: "au"}
});
but it still shows autocomplete options from Germany and France:(
Any suggestions?
How do I limit Google autocomplete results to city only? List only cities in the country var options = { types: ['(cities)'], componentRestrictions: {country: “us”} }; List all cities, states and regions in the country var options = { types: ['(regions)'], componentRestrictions: {country: “us”} };
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.
You can refresh Place IDs at no charge, by making a Place Details request, specifying only the place_id field in the fields parameter. This will trigger the Places Details - ID Refresh SKU. However, this request might also return NOT_FOUND status code.
Normally you select locations to search on Google Maps However, if special filtering is required, you can use “contains one of”, “contains none of”, “starts with” and “is not blank” operators to filter the task as in the examples above.
You need to pass the restrictions when you call the service, not when you create it. Here:
//create service
service = new google.maps.places.AutocompleteService();
//perform request. limit results to Australia
var request = {
input: 'Brisbane',
componentRestrictions: {country: 'au'},
};
service.getPlacePredictions(request, callback);
You can specify types, and componentRestrictions using AutocompletionRequest. Here is an example -
var service = new google.maps.places.AutocompleteService();
service.getPlacePredictions({ input: query, types: ['geocode'],
componentRestrictions:{ country: 'us' } },
function (predictions, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
var results = document.getElementById('results');
for (var i = 0, prediction; prediction = predictions[i]; i++) {
results.innerHTML += '<li>' + prediction.description + '</li>';
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With