Dynamic Country Filtering

This example demonstrates how to dynamically filter address suggestions by country. Selecting a country from the dropdown updates the `includedRegionCodes` request parameter, restricting the search to the selected country.

powered by
powered by Google

Implementation:

<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>
...