Customise Autocomplete Behaviour Dynamically
This example demonstrates how to dynamically update UI and behaviour options after the
component has been initialised. This powerful feature allows you to adapt the
component's appearance and functionality in real-time based on user interaction or
application state. 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 .
Current Options:
Step-by-Step Implementation
The key to dynamic customisation is the setOptions() method, which merges new settings with the existing configuration.
Here’s how to use it:
- Keep a Reference to the Instance: First, ensure you have a reference to the
PlacesAutocompleteinstance after it's created. - Call `setOptions()` with New Values: Use the
setOptions()method to pass an object containing the properties you want to change. For example, to update the placeholder, call"autocomplete.setOptions({ placeholder: \"New text...\" })". - Customise UI and Behavior: You can change UI elements like the placeholder and CSS classes, or adjust behavior
such as the
debouncedelay to control API requests. - Verify the Current Configuration: Call the
getOptions()method at any time to retrieve the current configuration object, which is useful for debugging and confirming that your changes have been applied.
Other Available Instance Methods
Beyond just options, you can dynamically control other aspects of the autocomplete instance.
clear()
Clears the input field and any visible suggestions, and refreshes the session token.
autocomplete.clear();destroy()
Removes event listeners and cleans up DOM elements created by the widget. Useful when the component is no longer needed.
autocomplete.destroy();setFetchFields(fields)
Dynamically updates the array of Place Data Fields to be requested.
autocomplete.setFetchFields(['displayName', 'types']);getFetchFields()
Retrieves the current array of Place Data Fields.
const currentFetchFields = autocomplete.getFetchFields();setRequestParams(params)
Dynamically updates the parameters sent to the Google Places Autocomplete API, such as region or language.
autocomplete.setRequestParams({
region: 'fr',
language: 'fr'
});getRequestParams()
Retrieves the current API request parameters.
const currentRequestParams = autocomplete.getRequestParams();<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>
...