Component Methods (Imperative API)

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.

Live Demo

Use the buttons below to interact with the component instance directly.

Methods Reference

The following methods are available on the component instance.

clear()
Clears the input, removes suggestions, and resets the session token.
() => void
focus()
Sets focus on the text input field.
() => void
getRequestParams()
Returns the current internal `requestParams` object being used for API calls.
() => RequestParams
setRequestParams()
Dynamically updates request parameters. Useful for changing search criteria (region, language, location bias, etc.). Parameters are merged with existing ones.
(params: Partial<RequestParams>) => void
setFetchFields()
Dynamically updates the Place Data Fields to fetch when a place is selected.
(fields: string[]) => void
getFetchFields()
Returns the current array of Place Data Fields that will be requested when a place is selected.
() => string[]
setOptions()
Dynamically updates the component's configuration options. Merges the provided options with existing settings.
(options: Partial<ComponentOptions>) => void
getOptions()
Returns the current validated options used by the component. Useful for inspecting configuration settings.
() => ComponentOptions
setInputValue()
Sets the input by finding and selecting a place for the given coordinates. Performs reverse geocoding to convert lat/lng to a place, then triggers `onResponse`. **Requires Geocoding API to be enabled.**
(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.

Common Use Cases

Here are some practical scenarios where component methods are particularly useful:

Form Integration

Clear the autocomplete input when a form is reset or submitted:

const handleFormReset = () => {
  autocompleteComponent?.clear();
  // Reset other form fields...
};

Dynamic Language Switching

Update the search language when the user changes their preferences:

const switchLanguage = (lang: string) => {
  autocompleteComponent?.setRequestParams({ 
    language: lang 
  });
};

Cost Optimisation

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'
]);

Geographic Filtering

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
    }
  });
};

Reverse Geocoding with Geolocation

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 Tower

Full Code Example

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