This example demonstrates how to integrate the Places Autocomplete component with a Google Map. When you select a place from the suggestions, the map will automatically pan to that location and place a marker.
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 { onMount } from 'svelte';
import { getGMapsLoader } from 'places-autocomplete-svelte/gmaps';
import { PlaceAutocomplete } from 'places-autocomplete-svelte';
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. Define the types for the libraries you will load.
type LoadedLibraries = {
Map: typeof google.maps.Map;
AdvancedMarkerElement: typeof google.maps.marker.AdvancedMarkerElement;
};
/**
* Install the Type Definitions for Google Maps
* npm install --save-dev @types/google.maps
*/
let mapElement: HTMLElement;
let map: google.maps.Map;
let marker: google.maps.marker.AdvancedMarkerElement;
let loadedLibs: LoadedLibraries | undefined;
const fetchFields = ['formattedAddress', 'addressComponents', 'location'];
// Options
const options: ComponentOptions = {
placeholder: 'Start typing your address',
distance: true,
distance_units: 'km',
clear_input: false,
debounce: 200
};
// Error handling
let placesError = $state('');
const onError = (error: string) => {
placesError = error;
};
// Response handler
const onResponse = (response: PlaceResult) => {
if (response.location) {
map.setCenter(response.location);
map.setZoom(15);
if (marker) {
marker.position = response.location;
} else {
if (loadedLibs) {
marker = new loadedLibs.AdvancedMarkerElement({
position: response.location,
map: map,
title: response.formattedAddress || 'Selected Location'
});
}
}
}
};
/**
* 2. Load the Google Maps JavaScript API and the required libraries on component mount.
*
*/
onMount(async () => {
const loader = getGMapsLoader(PUBLIC_GOOGLE_MAPS_API_KEY);
const { Map } = await loader.importLibrary('maps');
const { AdvancedMarkerElement } = await loader.importLibrary('marker');
loadedLibs = { Map, AdvancedMarkerElement };
const mapEl = document.getElementById('map');
// Check if the element was found before using it
if (mapEl && loadedLibs.Map) {
mapElement = mapEl; // This is now safe
map = new loadedLibs.Map(mapElement, {
center: { lat: 51.5072, lng: -0.1276 }, // Default to London
zoom: 10,
mapId: 'your-map-id'
});
} else {
// It's good practice to log an error if the element is missing
console.error('Failed to find the map element with ID "map"');
}
});
</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}
/>
<div id="map" class="h-96 w-full rounded-md"></div>