Restrict Google Places API to specific country

10,398

Solution 1

You're not passing the options correctly. Autocomplete takes two arguments, and you're passing three.

Specifically, in this line:

autocomplete[name] = new google.maps.places.Autocomplete(
    $('#'+name+' .autocomplete')[0], { types: ['geocode'] }, options);

your options parameter is unused, because you've passed { types: ['geocode'] } as the options.

So remove the extra argument:

var options = {
    types: ['geocode'],  // or '(cities)' if that's what you want?
    componentRestrictions: {country: "us"}
};
autocomplete[name] = new google.maps.places.Autocomplete(
    $('#'+name+' .autocomplete')[0], options);

Solution 2

If you want to integrate the Google Address API with only United Kingdom address. Please find the below address :

<script  type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places" async defer></script>

<script type="text/javascript>
var autocomplete;
function initialize() {
  autocomplete = new google.maps.places.Autocomplete(
      (document.getElementById('txtpostcode')),
      { types: ['geocode'] });
  autocomplete.setComponentRestrictions(
            {'country': ['uk']});
  google.maps.event.addListener(autocomplete, 'place_changed', function() {
  });
}
</script>
Share:
10,398
Martin Erlic
Author by

Martin Erlic

Personal Portfolio: http://www.martinerlic.com/ GitHub: https://github.com/seloslav LinkedIn: https://www.linkedin.com/in/martin-erlic/ Hey! My name is Martin. I am an experienced Software Engineer and Product Developer with a demonstrated history of working in the computer software industry. I am currently located in Victoria, BC. I love bringing products to life, from napkin sketch to working prototype and beyond. While I enjoy working in a collaborative team environment, I have extensive experience building and shipping my own products to the Google PlayStore and Apple App Store from the ground up. Want to build something great? Feel free to get in touch. I am interested in partnering with startups and small businesses to help them create lightning fast, strategic web and app solutions to help them grow. Skilled in Cloud Software, Databases, API Integrations, Web &amp; Mobile Applications and UI Design. Web, Android and iOS applications HTML, CSS, JavaScript, Java, .NET, Kotlin, Swift ReactJS, React-Native, Blazor, MongoDB, CosmosDB, Entity Framework, Realm, Parse-Server Strong engineering and business development professional with a Bachelor of Arts - BA focused in Economics from University of Victoria.

Updated on June 04, 2022

Comments

  • Martin Erlic
    Martin Erlic almost 2 years

    I'm trying to restrict autocomplete to a specific country, i.e. USA. How can I do this? I've tried the following below, by passing the variable options as a parameter into the initialization function:

       <script>
        var autocomplete = {};
        var autocompletesWraps = ['test', 'test2'];
    
        var test_form = { street_number: 'short_name', route: 'long_name', locality: 'long_name', administrative_area_level_1: 'short_name', country: 'long_name', postal_code: 'short_name' };
        var test2_form = { street_number: 'short_name', route: 'long_name', locality: 'long_name', administrative_area_level_1: 'short_name', country: 'long_name', postal_code: 'short_name' };
    
        function initialize() {
    
            var options = {
                types: ['(cities)'],
                componentRestrictions: {country: "us"}
            };
    
            $.each(autocompletesWraps, function(index, name) {
    
                if($('#'+name).length == 0) {
                    return;
                }
    
                autocomplete[name] = new google.maps.places.Autocomplete($('#'+name+' .autocomplete')[0], { types: ['geocode'] }, options);
    
                google.maps.event.addListener(autocomplete[name], 'place_changed', function() {
    
                    var place = autocomplete[name].getPlace();
                    var form = eval(name+'_form');
    
                    for (var component in form) {
                        $('#'+name+' .'+component).val('');
                        $('#'+name+' .'+component).attr('disabled', false);
                    }
    
                    for (var i = 0; i < place.address_components.length; i++) {
                        var addressType = place.address_components[i].types[0];
                        if (typeof form[addressType] !== 'undefined') {
                            var val = place.address_components[i][form[addressType]];
                            $('#'+name+' .'+addressType).val(val);
                        }
                    }
                });
            });
        }
    </script>
    
  • Martin Erlic
    Martin Erlic about 8 years
    Thanks. Didn't realize it only accepted two, but makes sense given that my last two were basically equivalent to one another.
  • melvin
    melvin almost 5 years
    your script type missing double qoutes at the end