This example demonstrates how to dynamically filter address suggestions by country. By
allowing users to select a country from a dropdown, you can restrict the autocomplete
search to that specific region. This is particularly useful for international forms, as
it prevents ambiguity and ensures more accurate, relevant results.
powered by
Formatted Address
Response JSON
Step-by-Step Implementation
Implementing dynamic country filtering involves updating the autocomplete parameters whenever
the user changes their country selection. This ensures that all subsequent address
searches are confined to the chosen region.
Here’s how it works:
Initialise with a Default Country: When the PlacesAutocomplete component is first mounted, it's configured with a default country (e.g., 'GB' for the
United Kingdom) using the includedRegionCodes parameter.
Handle Country Changes: An onchange event listener is attached to the country dropdown. When the user selects a new
country, the handleCountryChange function is triggered.
Update Request Parameters: Inside handleCountryChange, the setRequestParams method is called on the autocomplete instance. This method dynamically updates the includedRegionCodes with the newly selected country's code.
Clear the Input: Finally, autocomplete.clear() is called to reset the input field. This provides a clean slate for the user to start
typing a new address within the updated country context, preventing any leftover values
from a previous search.
<script>import{ PlacesAutocomplete }from'places-autocomplete-js';
document.addEventListener('DOMContentLoaded',()=>{try{let selectedCountry ='GB';// Default country// Available countries for selectionconst countries =[{code:'US',name:'United States'},{code:'GB',name:'United Kingdom'},{code:'CA',name:'Canada'},{code:'RU',name:'Russia'},{code:'FR',name:'France'},{code:'DE',name:'Germany'},];// Initialize the PlacesAutocomplete instanceconst autocomplete =newPlacesAutocomplete({containerId:'autocomplete-container',googleMapsApiKey:'YOUR_GOOGLE_MAPS_API_KEY',// Replace with your actual keyonResponse:(placeDetails)=>{
console.log(placeDetails);// Log the selected place details},onError:(error)=>{
console.error('Autocomplete Error:', error.message || error);},requestParams:{region:'GB',// Example regionincludedRegionCodes:['GB'],// Example countries},options:{placeholder:'Start typing your address...',clear_input:false// Retain input value after selection}});}catch(error){
console.error("Failed to initialize PlacesAutocomplete:", error.message);}// Get the select element and add an event listener for changesconst el = document.getElementById("country-select");
el.addEventListener("change", handleSelectChange);// Function to handle country selection changesfunctionhandleSelectChange(event){
selectedCountry = event.target.value;
console.log("Selected country:", selectedCountry);// Update the request parameters based on the selected country
autocomplete.setRequestParams({includedRegionCodes:[selectedCountry],});// Optionally, you can clear the input field when the country changes
autocomplete.clear();});</script>...<label for="country-select">Country:</label><select id="country-select"><option value="US">United States</option><option value="GB" selected>United Kingdom</option><option value="CA">Canada</option><option value="RU">Russia</option><option value="FR">France</option><option value="DE">Germany</option></select><div id="autocomplete-container"></div>...