Basic Usage

Integrating the Places Autocomplete component into your Svelte application is straightforward. This guide will walk you through the essential steps to get a functional autocomplete input up and running.

Prerequisites

Before you begin, ensure you have a Google Maps API Key with the Places API enabled. See the Getting Started guide for setup instructions.

Initialization Approaches

There are two ways to initialize the Google Maps loader with this component:

✨ Automatic (Recommended for Simple Projects)

Pass your API key directly to the component. Perfect for single-component usage.

  • ✓ Quick setup, minimal code
  • ✓ Ideal for single autocomplete instance
  • ✓ Component handles everything

⚙️ Manual (For Advanced Use Cases)

Initialize the loader once in a parent component. Use when you need multiple Google Maps libraries or components.

  • ✓ Multiple map components
  • ✓ Load multiple libraries (maps, marker, etc.)
  • ✓ Shared across routes

Automatic Initialization (Quick Start)

This is the simplest approach. Just import the component and pass your API key:

import { PlaceAutocomplete } from 'places-autocomplete-svelte';

Step 2: Handle the Response

The component communicates back to your application using the onResponse callback. This function is triggered whenever a user selects a place from the suggestions list. It receives the full place details object from the Google Places API.

let place = $state(null);

const onResponse = (response) => {
  // The Google Places API response object
  place = response;
};

Step 3: Render the Component

Finally, render the component in your markup. At a minimum, you need to pass the onResponse handler.

<PlaceAutocomplete {onResponse} />

Complete Example

Here is a complete, copy-and-paste example:

<script>
import { PlaceAutocomplete } from 'places-autocomplete-svelte';
import type { PlaceResult } from 'places-autocomplete-svelte/interfaces'; 

// Get API Key securely (e.g., from environment variables)
const PUBLIC_GOOGLE_MAPS_API_KEY = import.meta.env.VITE_PUBLIC_GOOGLE_MAPS_API_KEY;

// --- Event Handlers ---
const onResponse = (response: PlaceResult) => {
	console.log('Place Selected:', response);
};

const onError = (error: string) => {
	console.error('Places Autocomplete Error:', error);
};
</script>


<PlaceAutocomplete
    {PUBLIC_GOOGLE_MAPS_API_KEY}
    {onResponse}
    {onError}
/>

Manual Initialization (Advanced)

For applications using multiple Google Maps libraries or components, initialize the loader once in a parent component. This approach prevents "Loader must not be called again" errors and is more efficient.

⚡ Performance Tip

When using manual initialization, you can load multiple Google Maps libraries (e.g., maps, marker, geometry) in a single API call, which is more efficient than loading them separately.

Complete Example with Map Integration

<script>
import { browser } from '$app/environment';
import { PlaceAutocomplete } from 'places-autocomplete-svelte';
import { initialiseGMaps, setGMapsContext, importLibrary } from 'places-autocomplete-svelte/gmaps';
import type {PlaceResult,ComponentOptions } from 'places-autocomplete-svelte/interfaces';

let { data } = $props();
const PUBLIC_GOOGLE_MAPS_API_KEY = data?.PUBLIC_GOOGLE_MAPS_API_KEY;

// 1. Set the context for Google Maps. This should be done in the script's top-level scope.
setGMapsContext();

// 2. If we are in the browser, trigger the asynchronous loading process.
if (browser) {
	initialiseGMaps({
		key: PUBLIC_GOOGLE_MAPS_API_KEY,
		v: 'weekly' 
	}).catch((error: any) => {
		// ... handle error (already logged in initialiseGMaps)
	});
}

// --- Event Handlers ---
const onResponse = (response: PlaceResult) => {
	console.log('Place Selected:', response);
};

const onError = (error: string) => {
	console.error('Places Autocomplete Error:', error);
};

// --- Component Options ---
// See Properties for full list
const options: Partial<ComponentOptions> = {
	distance: true,
	distance_units: 'km',
	clear_input: true,
	placeholder: 'Start typing your address',
	classes: {
		li_current: 'bg-green-500',
	}
};

// --- Request Parameters ---
// See Request Parameters for full list
const requestParams = {
	region : 'GB',
	language : 'en-GB',      
};

// --- Fetch Fields ---
// Specify which fields to fetch from the Places API
const fetchFields = ['formattedAddress', 'addressComponents'];

</script>

<PlaceAutocomplete {options} {requestParams} {fetchFields} {onResponse} {onError} />

💡 Key Points

  • • Call setGMapsContext() at the top level (must be synchronous)
  • • Initialize in browser only using the browser check
  • • No need to pass PUBLIC_GOOGLE_MAPS_API_KEY to the component
  • • All child components automatically use the shared loader

Security Best Practices

Your Google Maps API Key is sensitive. To prevent unauthorized use and unexpected charges, you must restrict it.

🔐 Application Restrictions

In the Google Cloud Console, under Application restrictions, select HTTP referrers (web sites) and add your domain(s):

your-domain.com/*

🔑 API Restrictions

Under API restrictions, select Restrict key and choose only the APIs you use (e.g., Places API, Maps JavaScript API).

Google Maps Platform

Awards 2025 Winner

GitHub

2026 Places Autocomplete Svelte.