Whilst props offer a declarative way to configure the component, there are times when you need
to programmatically control its behaviour. For these advanced use cases, you can obtain a
direct reference to the component instance using Svelte's bind:this directive.
This imperative approach is useful for tasks such as clearing the input from an external button, integrating with form libraries, or calling methods from a parent component.
Use the buttons below to interact with the component instance directly.
The following methods are available on the component instance.
clear()() => voidfocus()() => voidgetRequestParams()() => RequestParamssetRequestParams()(params: Partial<RequestParams>) => voidsetFetchFields()(fields: string[]) => voidgetFetchFields()() => string[]setOptions()(options: Partial<ComponentOptions>) => voidgetOptions()() => ComponentOptionssetInputValue()(latitude: number, longitude: number) => Promise<void>⚠️ Geocoding API Required
The setInputValue() method requires the Geocoding API to be enabled in your Google Cloud Console project. This method performs reverse geocoding to
convert coordinates to a place, then fetches place details and triggers the onResponse callback.
Here are some practical scenarios where component methods are particularly useful:
Clear the autocomplete input when a form is reset or submitted:
const handleFormReset = () => {
autocompleteComponent?.clear();
// Reset other form fields...
};Update the search language when the user changes their preferences:
const switchLanguage = (lang: string) => {
autocompleteComponent?.setRequestParams({
language: lang
});
};Dynamically adjust which fields to fetch based on user needs to save API costs:
// For basic display, fetch minimal fields
autocompleteComponent?.setFetchFields(['formattedAddress']);
// For detailed mapping, fetch more data
autocompleteComponent?.setFetchFields([
'formattedAddress', 'location', 'viewport', 'types'
]);Update location bias when user selects a different region or moves the map:
const updateLocationBias = (lat: number, lng: number) => {
autocompleteComponent?.setRequestParams({
locationBias: {
lat: lat,
lng: lng
radius: 5000 // 5km radius
}
});
};Set the input using the user's current location or specific coordinates. Requires the Geocoding API to be enabled:
// Use browser geolocation
navigator.geolocation.getCurrentPosition(async (position) => {
try {
await autocompleteComponent.setInputValue(
position.coords.latitude,
position.coords.longitude
);
console.log('Location set successfully');
} catch (error) {
console.error('Failed to set location:', error);
}
});
// Or set a specific landmark
await autocompleteComponent.setInputValue(48.8584, 2.2945); // Eiffel TowerThe example below shows how to bind to the component instance and call its methods from buttons.
<script lang="ts">
import { PlaceAutocomplete } from 'places-autocomplete-svelte';
import type { PlaceResult, ComponentOptions, RequestParams } from 'places-autocomplete-svelte/interfaces';
let autocompleteComponent: PlaceAutocomplete | undefined = $state(undefined);
// --- Event Handlers ---
const handleResponse = (response: PlaceResult) => {
console.log('Place Selected:', response);
};
const handleError = (error: string) => {
console.error('Places Autocomplete Error:', error);
};
</script>
<PlaceAutocomplete
bind:this={autocompleteComponent}
{PUBLIC_GOOGLE_MAPS_API_KEY}
{onError}
{onResponse}
/>
<div class="controls">
<button onclick={() => autocompleteComponent?.clear()}>Clear</button>
<button onclick={() => autocompleteComponent?.focus()}>Focus Input</button>
<button onclick={() => console.log(JSON.stringify(autocompleteComponent?.getRequestParams(), null, 2))}>
Get Request Params
</button>
</div>