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

Locate Control

Previous Next

A button that finds the user's position, flies there and can keep following it.

<script lang="ts">
	import { Map, MapControlContainer, MapLocateControl } from '$lib/components/ui/map/index.js';

	let message = $state('Press the locate button');

	function showFix(position: GeolocationPosition) {
		const { latitude, longitude, accuracy } = position.coords;
		message = `${latitude.toFixed(4)}, ${longitude.toFixed(4)} (within ${Math.round(accuracy)} m)`;
	}

	// Browser error text varies; show the same plain message on every platform.
	const GEOLOCATION_MESSAGES: Record<number, string> = {
		1: 'Location access was denied',
		2: 'Your position is not available',
		3: 'Finding your position took too long'
	};

	function showError(error: GeolocationPositionError | Error) {
		const code = 'code' in error ? error.code : undefined;
		message = (code && GEOLOCATION_MESSAGES[code]) || 'Your location is not available';
	}
</script>

<div class="relative size-full">
	<Map class="size-full" viewport={{ center: [0, 20], zoom: 1.5, bearing: 0, pitch: 0 }}>
		<MapControlContainer position="top-right">
			<MapLocateControl onlocationfound={showFix} onerror={showError} />
		</MapControlContainer>
	</Map>
	<p
		class="absolute top-3 left-3 max-w-[70%] rounded-md bg-background/90 px-2 py-1 font-mono text-xs shadow"
		aria-live="polite"
	>
		{message}
	</p>
</div>

Press the button and the browser asks for permission to share the user’s location. On the first fix the map flies there and a pulsing dot marks the spot. The map zooms in to zoom if it is further out, and never zooms out.

The location is only requested when the button is pressed, never on page load.

Usage

Place the control inside a Control Container.

<script lang="ts">
	import { Map, MapControlContainer, MapLocateControl } from '$lib/components/ui/map/index.js';
</script>

<Map class="h-96">
	<MapControlContainer position="top-right">
		<MapLocateControl />
	</MapControlContainer>
</Map>

Following the user

Set watch to keep tracking the position. The dot moves with every fix, and the camera stays where the user leaves it. Press the button again to stop. In this mode the button is a toggle, so it has aria-pressed and its label changes to “Stop following my location”.

<MapLocateControl watch positionOptions={{ enableHighAccuracy: true }} />

positionOptions goes straight to the browser’s Geolocation API.

Positions and errors

onlocationfound gets every GeolocationPosition, with the accuracy, heading and speed the browser reports. onerror is called when the user denies permission, the browser has no fix, the request times out, or the browser cannot share a location at all. Without onerror, errors are logged to the console.

<MapLocateControl
	onlocationfound={(position) => (accuracy = position.coords.accuracy)}
	onerror={(error) => (message = error.message)}
/>

Status

The button’s data-status attribute holds a LocateStatus:

  • idle: nothing requested yet, or following stopped.
  • locating: waiting for the first fix. The button shows a spinner and aria-busy.
  • found: one position was found.
  • following: watch is on and positions keep coming.
  • error: the last request failed. The icon shows a crossed-out target.

The dot

The dot is a pulsing marker in the theme’s primary colour, labelled “Your location” for screen readers. Set showMarker={false} to hide it and draw your own from onlocationfound.

Reduced motion

When the user prefers reduced motion, the map jumps to the position instead of flying, and the dot stops pulsing.

API Reference

MapLocateControl

Props

NameTypeDescription
watch booleanKeep following the position until pressed again. Defaults to false.
zoom numberZoom to fly to on the first fix; the map never zooms out for it. Defaults to 14.
showMarker booleanShow a pulsing dot where the user is. Defaults to true.
positionOptions PositionOptionsPassed to the Geolocation API.

Events

NameTypeDescription
onlocationfound (position: GeolocationPosition) => voidCalled with every position fix.
onerror (error: LocateError) => voidPermission denied, no fix, timeout, or no Geolocation API. Logged when unset.
Fullscreen Control Basemap Control

On This Page

UsageFollowing the userPositions and errorsStatusThe dotReduced motionAPI Reference

Handcrafted by Oggy. The source code is on GitHub.