Dynamic UI and Behavior Options

This example demonstrates how to dynamically update UI and behavior options after the component has been initialised. Use the buttons below to see the setOptions() method in action.

The setOptions(options) method allows you to merge new options with the current configuration. For a full list of available options, see the documentation .

powered by
powered by Google

Current Options:

Implementation:

<script>
import { PlacesAutocomplete } from 'places-autocomplete-js';

document.addEventListener('DOMContentLoaded', () => {
  try {
    const autocomplete = new PlacesAutocomplete({
      containerId: 'autocomplete-container',
      googleMapsApiKey: 'YOUR_GOOGLE_MAPS_API_KEY', // Replace with your actual key
      onResponse: (placeDetails) => {
        console.log('Place Selected:', placeDetails);
      },
      onError: (error) => {
        console.error('Autocomplete Error:', error.message || error);
      },
       options:{
            placeholder: 'Search for places...',
            distance: true,        // Enable distance display
            distance_units: 'miles' // Display distance in miles (can also be 'km')
        },
         requestParams: {
            // Define the origin point for distance calculations
            origin: {
                lat: 37.7749, // Example: San Francisco, CA
                lng: -122.4194
            },
            // Optional: Bias results towards a region, e.g., United States
            region: 'US',
            includedRegionCodes: ['US']
        }
    });

    updateCurrentOptionsDisplay();
  } catch (error) {
    console.error("Failed to initialize PlacesAutocomplete:", error.message);
  }

  /**
   * Sets a random placeholder text for the autocomplete input
   * This demonstrates how to dynamically change the UI options after initialization.
   */
  function setPlaceholder() {
    if (!autocomplete) return;
    let pl = [
      'Trouver une adresse...',
      'Encontrar una dirección...',
      'Trova un indirizzo...',
      'Start typing an address...'
    ];
    autocomplete.setOptions({ placeholder: pl[Math.floor(Math.random() * pl.length)] });
    updateCurrentOptionsDisplay();
  }

  /**
   * Sets the background color of the input field to green
   * This demonstrates how to dynamically change the UI options after initialization.
   */
  function setBgRed() {
    if (!autocomplete) return;
    autocomplete.setOptions({ classes: { input: 'border-1 w-full rounded-md border-0 shadow-sm bg-green-200 px-4 py-2.5 pl-10 pr-20 text-gray-900 ring-1 ring-inset ring-gray-300 focus:ring-2 sm:text-sm' } });
    updateCurrentOptionsDisplay();
  }

  /**
   * Sets the debounce delay for the autocomplete
   * This controls how long to wait before sending a request after the user stops typing.
   * @param delay
   */
  function setDebounce(delay) {
    if (!autocomplete) return;
    autocomplete.setOptions({ debounce: delay });
    updateCurrentOptionsDisplay();
  }

  /**
   * Updates the current options display
   */
  function updateCurrentOptionsDisplay() {
    if (!autocomplete) return;
      currentOptionsOutput = JSON.stringify(autocomplete.getOptions(), null, 2);
    }  
  });

</script>

...
<div id="autocomplete-container"></div>
<div id="dynamic-options-container"></div>
<button on:click={setFrenchPlaceholder}>Set French Placeholder</button>
<button on:click={setDefaultPlaceholder}>Set Default Placeholder</button>
<button on:click={addLabel}>Add Label "Your Location:"</button>
<button on:click={removeLabel}>Remove Label</button>
<h3>Current Options:</h3>
<pre>{currentOptionsOutput}</pre>
...