Dynamic Country Filtering for Enhanced Accuracy
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 eliminates ambiguity and ensures more accurate, relevant results.
powered by
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
PlacesAutocompletecomponent is first mounted, it's configured with a default country (e.g., 'GB' for the United Kingdom) using theincludedRegionCodesparameter. - Handle Country Changes: An
onchangeevent listener is attached to the country dropdown. When the user selects a new country, thehandleCountryChangefunction is triggered. - Update Request Parameters: Inside
handleCountryChange, thesetRequestParamsmethod is called on the autocomplete instance. This method dynamically updates theincludedRegionCodeswith 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 selection
const 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 instance
const autocomplete = new PlacesAutocomplete({
containerId: 'autocomplete-container',
googleMapsApiKey: 'YOUR_GOOGLE_MAPS_API_KEY', // Replace with your actual key
onResponse: (placeDetails) => {
console.log(placeDetails); // Log the selected place details
},
onError: (error) => {
console.error('Autocomplete Error:', error.message || error);
},
requestParams: {
region: 'GB', // Example region
includedRegionCodes: ['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 changes
const el = document.getElementById("country-select");
el.addEventListener("change", handleSelectChange);
// Function to handle country selection changes
function handleSelectChange(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>
...