shadcn-svelte map
DocsComponentsBlocks
Get Started
  • Introduction
  • Installation
Guides
  • Theming
  • Drawing
  • Accessibility
  • Performance
  • Content Security Policy
Core
  • Map
  • Control Container
Markers
  • Marker
  • Popup
  • Point Layer
Data
  • GeoJSON
  • Shapes
  • Route
  • Arc
  • Cluster Layer
  • Heatmap
Controls
  • Zoom Control
  • Compass Control
  • Scale Control
  • Fullscreen Control
  • Locate Control
  • Basemap Control
  • Search Control
  • Draw Control
More
  • Place Autocomplete
  • Utilities

Place Autocomplete

Previous Next

A place search box that suggests addresses and places as you type, with or without a map.

<script lang="ts">
	import * as Card from '$lib/components/ui/card/index.js';
	import { PlaceAutocomplete, type Place } from '$lib/components/ui/place-autocomplete/index.js';

	let place = $state<Place | null>(null);
</script>

<div class="flex size-full flex-col items-center gap-4 p-6">
	<PlaceAutocomplete
		class="w-72"
		placeholder="Search a city or street"
		onselect={(p) => (place = p)}
	/>
	{#if place}
		<Card.Root class="w-72">
			<Card.Header>
				<Card.Title>{place.name}</Card.Title>
				<Card.Description>{place.description || place.kind}</Card.Description>
			</Card.Header>
			<Card.Content class="font-mono text-xs text-muted-foreground">
				{place.position[1].toFixed(4)}, {place.position[0].toFixed(4)}
			</Card.Content>
		</Card.Root>
	{/if}
</div>

PlaceAutocomplete is a search box with a list of suggestions. It asks the Photon geocoder, which searches OpenStreetMap data. It needs no API key and no map, so you can use it in any form, such as a shipping address or a store finder.

Installation

It is its own registry item, so you can add it without the map:

pnpm dlx shadcn-svelte@latest add https://shadcn-svelte-map.vercel.app/r/place-autocomplete.json
npx shadcn-svelte@latest add https://shadcn-svelte-map.vercel.app/r/place-autocomplete.json
yarn dlx shadcn-svelte@latest add https://shadcn-svelte-map.vercel.app/r/place-autocomplete.json
bunx --bun shadcn-svelte@latest add https://shadcn-svelte-map.vercel.app/r/place-autocomplete.json

Usage

<script lang="ts">
	import { PlaceAutocomplete, type Place } from '$lib/components/ui/place-autocomplete/index.js';

	let place = $state<Place | null>(null);
</script>

<PlaceAutocomplete onselect={(next) => (place = next)} />

{#if place}
	<p>{place.name} at {place.position[1]}, {place.position[0]}</p>
{/if}

Bind query if you need the text in the box. Picking a place sets it to the place’s name.

Searching

The box waits until the user stops typing, then sends one request. While a request is in flight, a new keystroke aborts it, so an old answer never replaces a newer one. The defaults:

  • debounce: 300 ms after the last keystroke.
  • minLength: 2 characters. Shorter text clears the list.
  • limit: 6 results.
  • timeout: 8000 ms, after which the request gives up and the list shows an error.

lang asks for results in default, de, en or fr. near is a function that returns a [longitude, latitude] position. It is read when each search starts, and results near it rank higher.

Network and response errors go to onerror. Without it the box logs them to the console. PlaceSearch on its own stays silent unless you pass onerror. Aborted searches are not errors and never reach it.

The keyboard works as you would expect: arrow keys move through the list, Enter picks, and Escape closes the list or, if it is already closed, clears the box.

With a map

The box has no tie to a map. To move a map, set its viewport when a place is picked:

<script lang="ts">
	import { Map, MapMarker, type MapViewport } from '$lib/components/ui/map/index.js';
	import { PlaceAutocomplete, type Place } from '$lib/components/ui/place-autocomplete/index.js';

	const ZOOM = 14;

	let viewport = $state<MapViewport>({ center: [2.1734, 41.3851], zoom: 11, bearing: 0, pitch: 0 });
	let place = $state<Place | null>(null);

	function show(next: Place) {
		place = next;
		viewport = { ...viewport, center: next.position, zoom: ZOOM };
	}
</script>

<div class="relative size-full">
	<Map class="size-full" bind:viewport>
		{#if place}
			<MapMarker lngLat={place.position} aria-label={place.name} />
		{/if}
	</Map>
	<PlaceAutocomplete class="absolute top-3 left-3" near={() => viewport.center} onselect={show} />
</div>

Inside a Map, the Search Control does this for you. It flies to points, fits areas to the view, and prefers results near the middle of the map.

Your own server

The public Photon instance is shared. For heavy traffic, run your own or use another provider that speaks the Photon API, and pass its base URL:

<PlaceAutocomplete baseUrl="https://geocoder.example.com" />

The site needs to allow the geocoder in its Content Security Policy. PHOTON_ORIGIN is the public instance’s origin, ready for connect-src. See Content Security Policy.

Helpers

The item also exports what the box is built from, for when you need your own UI.

PlaceSearch

A class with the search logic and no markup. Call search(query) on every keystroke and read the reactive fields.

<script lang="ts">
	import { PlaceSearch } from '$lib/components/ui/place-autocomplete/index.js';

	const places = new PlaceSearch(() => ({ limit: 5, lang: 'en' }));
	$effect(() => () => places.cancel());
</script>

<input aria-label="Search places" oninput={(event) => places.search(event.currentTarget.value)} />

{#if places.status === 'loading'}
	<p>Searching…</p>
{:else}
	{#each places.results as place (place.id)}
		<p>{place.name}</p>
	{/each}
{/if}
  • results: the places from the last search.
  • status: 'idle', 'loading', 'done' or 'error'.
  • error: the last error, or null.
  • search(query): starts a debounced search. Text shorter than minLength clears the results.
  • cancel(): stops a pending search and aborts the request in flight. Call it when your component goes away.

The constructor takes a function that returns the options, so it reads your latest props for every search. The options are baseUrl, limit, lang, debounce, minLength, near, timeout and onerror.

Photon helpers

  • photonSearchUrl({ query, baseUrl, limit, lang, near }) returns the search URL as a string. Use it to call Photon from a server route.
  • parsePhotonResponse(body) turns a Photon response into Place[]. It skips results without a name or a point, and drops duplicates. It throws when the body is not a GeoJSON feature collection.
  • PHOTON_URL is the default base URL. PHOTON_ORIGIN is the origin for your CSP.

Place

Each result is a Place:

  • id: a stable OpenStreetMap id, such as W783052052.
  • name and description: the place’s name, and its street, city and country without repeating the name.
  • kind: the OpenStreetMap kind, such as city, street or house.
  • position: [longitude, latitude], typed as PlacePosition.
  • bounds: south-west and north-east corners, when the place covers an area.

API Reference

PlaceAutocomplete

Props

NameTypeDescription
query bindablestringText in the search box. Defaults to ''.
placeholder stringHint shown in the empty search box. Defaults to 'Search places'.
label stringName of the search box for screen readers. Defaults to 'Search places'.
baseUrl stringPhoton base URL. Defaults to the public instance.
limit numberMost results to show.
lang stringLanguage of the results: `default`, `de`, `en` or `fr`.
debounce numberMilliseconds to wait after the last keystroke.
minLength numberFewest characters that start a search.
timeout numberMilliseconds before a request gives up.
near () => PlacePosition | undefinedPrefer results near this position, read when a search starts.
class string

Events

NameTypeDescription
onselect (place: Place) => voidCalled with the place the user picks.
onerror (error: Error) => voidNetwork and response errors. Logged when unset.
Draw Control Utilities

On This Page

InstallationUsageSearchingWith a mapYour own serverHelpersPlaceSearchPhoton helpersPlaceAPI Reference

Handcrafted by Oggy. The source code is on GitHub.