Basic Usage

Integrating the Places Autocomplete component into your Svelte application is straightforward. This guide walks 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. Refer to the Getting Started guide for setup instructions.

Initialisation Approaches

There are two ways to initialise 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 required
  • ✓ Ideal for a single autocomplete instance
  • ✓ Component handles everything

⚙️ Manual (For Advanced Use Cases)

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

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

Automatic Initialisation (Quick Start)

This is the simplest approach—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's 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 Initialisation (Advanced)

For applications using multiple Google Maps libraries or components, initialise 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 initialisation, 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)
  • • Initialise 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 unauthorised 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).