Basic example

This example demonstrates the basic integration of the Places (New) Autocomplete Svelte component, showing how to display the component and retrieve the selected place details.

powered by
powered by Google

Code

Copy and paste the following code into your Svelte application and replace ___YOUR_API_KEY___ with your actual API key to start using the Places Autocomplete Svelte component.

<script>
import { PlaceAutocomplete } from 'places-autocomplete-svelte';
import type { 
	PlaceResult, 
	ComponentOptions, 
	RequestParams 
} 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;
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
	}
});

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

2025 Places Autocomplete Svelte.