I'm using Google Maps API to get autocomplete list of cities and countries (without other details), and it works exellent.
var input = document.getElementById('newAddress');
var options = {
types: ['(cities)']
};
autocomplete = new google.maps.places.Autocomplete(input, options);
Now I want to do exactly the same but to get only countries names. Somthing like replacing types: ['(cities)']
with types: ['(countries)']
...
(what I tried but didn't work)
What should I do in order to get only countries into my autocomplete?
As also mentioned in this SO answer, it is not currently possible to restrict Places Autocomplete results to specific cities/localities. Using the Places Autocomplete web service, you will need to define the location and radius parameter to restrict the results to that region by setting "strictbounds" to true.
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.
I've been playing around with the Google Autocomplete API for a bit and here's the best solution I could find for limiting your results to only countries:
var autocomplete = new google.maps.places.Autocomplete(input, options);
var result = autocomplete.getPlace();
console.log(result); // take a look at this result object
console.log(result.address_components); // a result has multiple address components
for(var i = 0; i < result.address_components.length; i += 1) {
var addressObj = result.address_components[i];
for(var j = 0; j < addressObj.types.length; j += 1) {
if (addressObj.types[j] === 'country') {
console.log(addressObj.types[j]); // confirm that this is 'country'
console.log(addressObj.long_name); // confirm that this is the country name
}
}
}
If you look at the result object that's returned, you'll see that there's an address_components array which will contain several objects representing different parts of an address. Within each of these objects, it will contain a 'types' array and within this 'types' array, you'll see the different labels associated with an address, including one for country.
There is no quick solution as Google only offers two type collections: ['(cities)'] and ['(regions)']
There is no ['(countries)'] available.
Documentation here: https://developers.google.com/places/documentation/autocomplete#place_types
EDIT:
You could as an alternative use an autocomplete plugin sourced from this url: http://www.geognos.com/api/en/countries/info/all.json
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