import { PlaceAutocomplete } from 'places-autocomplete-svelte'
You'll need a Google Maps API key with the Places API (New) enabled. Create or obtain your key from the Google Cloud Console.
Start using the component in your Svelte code.
<script>
import { PlaceAutocomplete } from 'places-autocomplete-svelte';
const PUBLIC_GOOGLE_MAPS_API_KEY = '___YOUR_API_KEY___';
// Response handler
let fullResponse = $state('')
let onResponse = (response) => {
fullResponse = response;
};
// Error handler
let pacError = '';
let onError = (error: string) => {
pacError = error;
};
</script>
{#if pacError}
<p class="error">{pacError}</p>
{/if}
<PlaceAutocomplete {onResponse} {onError} {PUBLIC_GOOGLE_MAPS_API_KEY} />
<p>Response Object: {JSON.stringify(fullResponse, null, 2)}</p>
This section explains how to customise the autocomplete behavior and placeholder text of the input field.
The `autocomplete` property controls the browser's built-in autocomplete functionality for the input field. By default, it's set to `off` to disable browser autocomplete, providing a more consistent experience with the Google Places (New) Autocomplete suggestions. However, you can change this behavior if needed.
const options = {
autocompete: 'on',
};
<PlaceAutocomplete
PUBLIC_GOOGLE_MAPS_API_KEY={PUBLIC_GOOGLE_MAPS_API_KEY}
{onResponse}
{options}
/>
The `autofocus` property controls the autofocus for the input field. By default, it's set to `false` to disable focusing the component input field. However, you can change this behavior if needed.
const options = {
autofocus: true,
};
<PlaceAutocomplete
PUBLIC_GOOGLE_MAPS_API_KEY={PUBLIC_GOOGLE_MAPS_API_KEY}
{onResponse}
{options}
/>
The `placeholder` property lets you customise the placeholder text displayed in the input field when it's empty.
const options = {
placeholder="Start typing your address",
};
<PlaceAutocomplete
PUBLIC_GOOGLE_MAPS_API_KEY={PUBLIC_GOOGLE_MAPS_API_KEY}
{onResponse}
{options}
/>