Search code examples
javascriptjquerygoogle-geocodergoogle-geocoding-api

Using Google maps geocoder with address and component restrictions for country


I have a field on my form that is using the google autocomplete feature

new window.google.maps.places.Autocomplete(location, { types: ['geocode'] });

but if the user doesn't select a dropdown from the autocomplete I need google maps geocoder to search when the form is submitted. I want my user to select either a street, town, city, neighborhood, etc anywhere in the world!

var navbarGeocoder = new google.maps.Geocoder();
navbarGeocoder.geocode({
      'address': location.value
    }, function(results, status) {

But now I want to be able to limit the geocoder to the US (street, neighborhood, city, town, etc.) with the componentRestriction of the country (US), but when I try this below it just hangs!

var navbarGeocoder = new google.maps.Geocoder();
navbarGeocoder.geocode({
  'address': location.value
}, {
  componentRestrictions: {
    country: ' US'
  }
}, function(results, status) {

  if (status === google.maps.GeocoderStatus.OK) {
    // do something
  } else {
    // do something
  }

});

Is there a proper way to add the component restriction and still have the address field? Any help would be appreciated!

I'm using this link to the google site for doc, is there a field in the component restrictions that acts like the address field?


Solution

  • From looking over the documentation you supplied I think your problem might actually be pretty simple - though I have yet to test it myself. Anyway, if you scroll up to the "Geocoding requests" section you'll see the following code.

    {
     address: string,
     location: LatLng,
     placeId: string,
     bounds: LatLngBounds,
     componentRestrictions: GeocoderComponentRestrictions,
     region: string
    }
    

    So, I think you just need to put the componentRestrictions field in the same array as the actual address. Let me know if it helps :)

    So instead of what you posted, try this...

    var navbarGeocoder = new google.maps.Geocoder(); 
    navbarGeocoder.geocode({ 
        'address': location.value, 
        componentRestrictions: { 
            country: ' US' 
        } 
    },