DEV Community

Cover image for Implement and Optimize Autocomplete with Google Places API

Implement and Optimize Autocomplete with Google Places API

Gaël on November 27, 2020

The Google Places API is a service that returns places predictions using HTTP requests. The service can be used to provide an autocomplete functio...
Collapse
 
nicky_zintchenko_d012b3b7 profile image
Nicky Zintchenko

Hi,

Great article, loved it!

I'm trying to limit the suggestions and the selection to a certain country, and I encounter a problem where some addresses in a certain country are returned with Country: NULL, and then they're not selectable.

I'm guessing this is related to places that are under some dispute..

If I add NULL as a "Country", how can I know to which places did I just opened up to? Is there a list or a map showing places with a country:NULL?

Thanks!

Collapse
 
gaelsimon profile image
Gaël

Hi @nicky_zintchenko_d012b3b7
Whether you're implementing Autocomplete Widget or AutocompleteService, you can use the componentRestrictions parameter to filter results to show only those places within a specified country.

For the Autocomplete Widget, set the restriction like this:

const autocomplete = new google.maps.places.Autocomplete(inputID, {
    componentRestrictions: { country: ["fr", "es"] }   
  });
Enter fullscreen mode Exit fullscreen mode

and for the AutocompleteService:

const autocompleteService = new google.maps.places.AutocompleteService();
autocompleteService.getPlacePredictions({
  input: 'Address user input',
  componentRestrictions: { country: ["fr", "es"] },
  sessionToken: sessionToken
}, displaySuggestions);
Enter fullscreen mode Exit fullscreen mode

Do you have an example of an address which returns a country: null attribute?

If you really need to get the Country from a known LatLng, you are also able to geocode the suggestion.

const geocoder = new google.maps.Geocoder();
geocoder
    .geocode({location: {lat: 40.731, lng: -73.997}})
    .then((response) => {
        if (response.results[0]) {
            //get country here. example: https://stackoverflow.com/a/19248156/1428755
        }
    })
Enter fullscreen mode Exit fullscreen mode

Hope this help.

Collapse
 
raj2852 profile image
Rajdip Mondal

Hey friend! Rajdip here. Could you confirm for me if the "places autocomplete API" is free to use or is a billed service? I am from India.

Collapse
 
gaelsimon profile image
Gaël

Hello Rajdip, It depends on your usage. You will have to enable the billing for your account but, for each Google Maps Platform account, a $200 USD credit is available each month. More details here: developers.google.com/maps/documen...