How to Restrict Address Autocomplete to a Specific Country

Overview

Would you like to restrict Address Autocomplete functionality to a specific country? When you create your own unique address schemes for a desired country you would also want to make sure that the Address Autocomplete only searches in that country. In this article, we’re going to show you how to achieve this using JavaScript.

Setup

For the purpose of this documentation, we’ve already created a unique address Scheme for Canada by following the steps from this tutorial.

Once we’ve added our additional address scheme, we’ve then selected the Scheme for our Address field inside the form builder.

set your address scheme

In addition to this, we’ve also turned on Enable Address Autocomplete from the Advanced tab of the Address field.

click the button to Enable Address Autocomplete

Adding the snippet

Once you’ve set up and saved your form, it’s now time to add the snippet. If you need any help with adding snippets to your site, please check out this tutorial.


/**
 * Restrict address autocomplete to a specific country
 *
 * @link https://wpforms.com/developers/how-to-restrict-address-autocomplete-to-a-specific-country/
 */

function wpf_dev_geo_autocomplete_default_country( ) {
?>
<script type="text/javascript">
 	jQuery(function($){
		
        var formID = 2757; // Change form ID
		
        var addressFieldID = 21; // Change address field ID 
		
	    // Find field place by country
	    var stateField = window.WPFormsGeolocationGooglePlacesAPI.findFieldPlaceByPolitical($( `#wpforms-${formID}-field_${addressFieldID}-state` )[0]);

            // Put a country code here according to this list: https://en.wikipedia.org/wiki/List_of_ISO_3166_country_codes

	    // Set default autocomplete country to Canada
	    stateField.autocomplete.setComponentRestrictions({
		    'country': [ 'ca' ],
	    });	
    });
</script>
<?php
}
add_action( 'wpforms_wp_footer_end', 'wpf_dev_geo_autocomplete_default_country', 30 );

There are three items you need to update in the snippet to match your specific requirements.

  1. var formID = 2757;
  2. var addressFieldID = 21;
  3. ‘country’: [ ‘ca’ ],

These will need to be updated to match your own form ID, field ID, and the country you want the Address Autocomplete to only search in.

To find your form and field IDs, please check out this tutorial.

For assistance in finding the 2-letter country code for your specific country, please checkout this documentation.

And that’s it, now when an address is typed in, the autocomplete feature will only search inside the country you specified.

Would you like to also restrict the Phone field to a specific country? Take a look at our article on How to Restrict Countries Inside Smart Phone Form Fields.

Action Reference: wpforms_wp_footer_end