Search code examples
wordpressgoogle-apiautocompletecontact-form-7

Google Places autocomplete Australia-only restriction in Wordpress


I have installed Address autocomplete Contact Form 7 in my Wordpress site and insert google API key in there to autocomplete state and suburb fields.

How do I restrict Google Places to Australia only? Here is the code I'm using

                  window.onload = function initialize_gpa() {


                      var options = {
                         componentRestrictions: {country: 'au'}
                      };
                       var acInputs = document.getElementsByClassName("wpcf7-autocomplete");

                            for (var i = 0; i < acInputs.length; i++) {

                                var autocomplete = new google.maps.places.Autocomplete(acInputs[i],options[i]);
                                autocomplete.inputId = acInputs[i].id;

                                google.maps.event.addListener(autocomplete, 'place_changed', function () {

                                });
                            }

                  }

Solution

  • It looks like your issue is that you are treating 'options' as an indexed array: 'options[i]'. This will return 'undefined' as options is an object with only one key - 'componentRestrictions'.

    Instead call 'new google.maps.places.Autocomplete' with the base 'options' object:

    var autocomplete = new google.maps.places.Autocomplete(acInputs[i],options);