Retain Input Value After Selection

This example demonstrates the flexibility of the PlacesAutocompleteJs library by allowing you to dynamically update its UI options after initialization. Use the buttons below to change the input field's placeholder text and to add or modify a label above it using the setOptions() public method.

The setOptions(options) dynamically updates the UI behavior and appearance options of the widget. The provided options object will be combined with the library's default options .

powered by
powered by Google

Current Options:

Example Code:

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