Skip to the content.

Places (New) Autocomplete Svelte

npm version License: MIT

A flexible and customizable Svelte component leveraging the Google Maps Places Autocomplete API (New) to provide a user-friendly way to search for and retrieve detailed address information within your SvelteKit applications.

This component handles API loading, session tokens, fetching suggestions, and requesting place details, allowing you to focus on integrating the results into your application. Includes features like debounced input, highlighting of matched suggestions, extensive customization via CSS classes, and full TypeScript support.

Also Available: Standalone JavaScript Library

Need this functionality for a non-Svelte project? Check out our companion vanilla JavaScript library, places-autocomplete-js, which offers the same core Google Places (New) Autocomplete features. View places-autocomplete-js on GitHub

Features

Demo

See a live demo of the component in action: Basic Example

Reactive parameters - change the search criteria based on user input, like filtering by country or change results language.

Customise request parameters - construct a requestParams object and control various aspects of the search, including language, region, and more.

Retain Input Value After Selection - This example demonstrates how to configure the Places (New) Autocomplete Svelte component to keep the selected address visible in the input field after a suggestion is chosen. It utilises the options.clear_input = false setting.

A video demonstrating the Places Autocomplete Svelte component in action, showing address suggestions and selection.

Requirements

Installation

npm install places-autocomplete-svelte
# or
yarn add places-autocomplete-svelte

Basic Usage

  1. Replace '___YOUR_API_KEY___' with your actual Google Maps API Key.
  2. Use the onResponse callback to handle the response.
<script>
import { PlaceAutocomplete } from 'places-autocomplete-svelte';
import type { PlaceResult, ComponentOptions, RequestParams } from 'places-autocomplete-svelte/interfaces'; // Adjust path if needed


// Get API Key securely (e.g., from environment variables)
const PUBLIC_GOOGLE_MAPS_API_KEY = import.meta.env.VITE_PUBLIC_GOOGLE_MAPS_API_KEY;
let fullResponse: PlaceResult | null = $state(null);
let placesError = $state('');


// --- Event Handlers ---
const handleResponse = (response: PlaceResult) => {
	console.log('Place Selected:', response);
	fullResponse = response;
	placesError = ''; // Clear previous errors
};

const handleError = (error: string) => {
	console.error('Places Autocomplete Error:', error);
	placesError = error;
	fullResponse = null; // Clear previous results
};

// --- Configuration (Optional) ---

// Control API request parameters
const requestParams: Partial<RequestParams> = $state({
	region: 'GB', // Example: Bias results to Great Britain
	language: 'en-GB',
	// includedRegionCodes: ['GB'], // Example: Only show results in the specified regions,
	// includedPrimaryTypes: ['address'], // Example: Only show addresses
});

// Control which data fields are fetched for Place Details (affects cost!)
const fetchFields: string[] = $state(['formattedAddress', 'addressComponents', 'displayName']);

// Control component appearance and behavior
const options: Partial<ComponentOptions> = $state({
	placeholder: 'Start typing your address...',
	debounce: 200, // Debounce input by 200ms (default is 100ms)
	distance: true, // Show distance if origin is provided in requestParams
	classes: {
		// Example: Override input styling and highlight class
		input: 'my-custom-input-class border-blue-500',
		highlight: 'bg-yellow-200 text-black', // Customize suggestion highlighting
	},
    clear_input: false, // Overriding the default value to keep the input value after selecting a suggestion. The value of the input will be the value of `formattedAddress`
});

</script>

{#if placesError}
    <div class="error-message" role="alert">
        Error: {placesError}
    </div>
{/if}

<PlaceAutocomplete
    {PUBLIC_GOOGLE_MAPS_API_KEY}
    {requestParams}
    {fetchFields}
    {options}
    onResponse={handleResponse}
    onError={handleError}
/>

{#if fullResponse}
    <h2>Selected Place Details:</h2>
    <pre>{JSON.stringify(fullResponse, null, 2)}</pre>
{/if}

<style>
    /* Example of styling an overridden class */
    :global(.my-custom-input-class) {
        padding: 0.75rem;
        border-radius: 0.25rem;
        width: 100%;
        /* Add other styles */
    }
    .error-message {
        color: red;
        margin-bottom: 1rem;
    }
</style>

Props

| Prop | Type | Required | Default | Description | |—————————-|———————————|———-|——————————————-|—————————————————————————————————————–| | PUBLIC_GOOGLE_MAPS_API_KEY | string | Yes | - | Your Google Maps API Key with Places API enabled. | | fetchFields | string[] | No | [‘formattedAddress’, ‘addressComponents’] | Array of Place Data Fields to request when a place is selected. Affects API cost. | | requestParams | Partial | No | { inputOffset: 3, ... } | Parameters for the Autocomplete request. See AutocompletionRequest options. | | options | Partial | No | { debounce: 100, ... } | Options to control component behavior and appearance. See details below. | | onResponse | (response: PlaceResult) => void | Yes | - | Callback function triggered with the selected place details (PlaceResult object) after fetchFields is complete. | | onError | (error: string) => void | Yes | - | Callback function triggered when an error occurs (API loading, fetching suggestions, fetching details). |

Component Methods (Imperative API)

For advanced use cases, you can get a reference to the component instance using bind:this and call its methods directly. This is useful for controlling the component from a parent, such as clearing the input from an external button.

Example Setup:

<script lang="ts">
    import PlaceAutocomplete from 'places-autocomplete-svelte';
    let autocompleteComponent = $state(null); // This will hold the component instance
</script>

<PlaceAutocomplete bind:this={autocompleteComponent} ... />

<button onclick={() => autocompleteComponent.clear()}>Clear</button>
<button onclick={() => autocompleteComponent.focus()}>Focus Input</button>
<button onclick={() => console.log(JSON.stringify(autocompleteComponent.getRequestParams()))}>Get Request Params</button>

Available Methods:

Method Signature Description
clear() () => void Clears the input field, removes all suggestions, and resets the Google Places session token.
focus() () => void Programmatically sets focus on the text input field.
getRequestParams() () => RequestParams Returns the component’s current internal requestParams object. Useful for debugging or state inspection.

Options

Option Type Default Description  
placeholder string ’’ Placeholder text for the input field.  
debounce number 100 Delay in milliseconds before triggering autocomplete API request after user stops typing. Set to 0 to disable debouncing.  
distance boolean true Show distance from requestParams.origin in suggestions (if origin is provided).  
distance_units ‘km’ | ‘miles’ ‘km’ Units to display distance in.  
label string ’’ Optional label text displayed above the input field.  
autofocus boolean false Automatically focus the input field on mount.  
autocomplete string ‘off’ Standard HTML autocomplete attribute for the input field.  
classes Partial {} Object to override default CSS classes for various component parts. See Styling (options.classes) section for keys.  
clear_input Boolean true If true (default), clears the input field after a suggestion is selected. If false, the input field retains the formattedAddress of the selected place.  

Styling (options.classes)


You can customize the appearance of the component by providing your own CSS classes via the options.classes prop. The component uses Tailwind CSS utility classes by default. Provide an object where keys are the component parts and values are the class strings you want to apply. See styling for details.

Available Class Keys: The following keys can be used within the `options.classes object to target specific parts of the component:

Example:

const options = {
  classes: {
    input: 'form-input w-full rounded-md shadow-sm', // Replace default input style
    ul: 'absolute bg-white shadow-lg rounded-md mt-1 w-full z-10', // Custom dropdown style
    li_current: 'bg-blue-500 text-white', // Custom highlight style for selected item
    highlight: 'text-blue-700 font-semibold' // Custom style for matched text
  }
};

Events

TypeScript

This component is written in TypeScript and includes type definitions for props (Props, ComponentOptions, RequestParams, ComponentClasses) and the response (PlaceResult, AddressComponent). You can import these types from places-autocomplete-svelte/interfaces (adjust path if needed based on your setup).

Google Places API & Billing

Contributing

Contributions are welcome! Please feel free to open an issue or submit a pull request.

License

MIT