0

I'm developing my personal project and I'm working for first time with the Google Places API - I would like to retrict the user's post/search to each user's country.

So I need visitor from Australia just been able to get address results for "au", basically, but for each country.

Is there anything easier that this Getting visitors country from their IP to retrieve the visitors country and pass it as the componentRestrictions? Is it the best/recommendable way to do it?

Thanks ahead!

function initialize() {

 var input = document.getElementById('address');
  var options = {
   // fields: ["address_components", "geometry"],
    strictBounds: false,
    types: ["address"],
  componentRestrictions: { country: ["au","nz"] }
   };  
  
      var autocomplete = new google.maps.places.Autocomplete(input,options);
     

I forgot to mention that I'm using Nominatim to display the user location so maybe better using this to restrict?

 data.address['country_code']

1 Answers1

0

Solved by passing the nominatim country_code (I use that to retrieve user's location) to the Google component via geoLocationSuccess():

function geoLocationSuccess(pos) {
  // get user lat,long  
  var myLat = pos.coords.latitude,
    myLng = pos.coords.longitude,
    loadingTimeout;

  var loading = function () {
     $address.val("Fetching location...");   
  };

  loadingTimeout = setTimeout(loading, 600);

  var request = $.get(
    "https://nominatim.openstreetmap.org/reverse?format=json&lat=" +
      myLat +
      "&lon=" +
      myLng
  )
    .done(function (data) {
                            
      if (loadingTimeout) {
        clearTimeout(loadingTimeout);
        loadingTimeout = null;

        
        // Restrict Google Places API to this country?
        var countrycode = data.address['country_code'];
         var input = document.getElementById('address');
          var options = {
           // fields: ["address_components", "geometry"],
            strictBounds: false,
            types: ["address"],
          componentRestrictions: { country: countrycode }
           };  
  
      var autocomplete = new google.maps.places.Autocomplete(input,options);
      
     
     }
    })
    .fail(function () {
      // handle error
     alertify.error('We can“t access your device location.');
     $address.val("Type your location");         
    });

}