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

Map

Previous Next

The map root that owns the style, the camera, loading and errors, and shares the map with its children.

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

	let viewport = $state<MapViewport>({ center: [2.3522, 48.8566], zoom: 11, bearing: 0, pitch: 0 });
</script>

<div class="relative size-full">
	<Map class="size-full" bind:viewport />
	<p
		class="absolute top-3 left-3 rounded-md bg-background/90 px-2 py-1 font-mono text-xs shadow"
		aria-live="polite"
	>
		{viewport.center[1].toFixed(4)}, {viewport.center[0].toFixed(4)} · zoom {viewport.zoom.toFixed(
			1
		)}
	</p>
</div>

Map creates a MapLibre map inside a <div> and gives it to every component you put inside it. Give it a size with a class, such as h-96 or size-full. It loads MapLibre on the client only, so it is safe to render on the server.

Usage

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

<Map class="h-96" viewport={{ center: [13.405, 52.52], zoom: 11, bearing: 0, pitch: 0 }} />

Style

mapStyle takes a style URL, a style object, or { light, dark }. With a pair, the map follows the page theme and swaps styles when it changes. The default is an OpenFreeMap pair, which needs no API key.

<Map
	class="h-96"
	mapStyle={{
		light: 'https://tiles.openfreemap.org/styles/positron',
		dark: 'https://tiles.openfreemap.org/styles/dark'
	}}
/>

For a map that shows only your own data, pass BLANK_MAP_STYLE. It has no layers, so the map shows the theme background.

Layers you add with this library survive a style swap. Markers, popups and controls are not remounted.

Camera

viewport holds center, zoom, bearing and pitch. Bind it to read the camera as the user moves the map, and assign to it to move the map.

For full control, pass viewport without binding it, together with onviewportchange. The map calls it with every proposed camera change, then shows whatever viewport holds. Here the zoom is kept between 10 and 15:

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

	const MIN_ZOOM = 10;
	const MAX_ZOOM = 15;

	let viewport = $state<MapViewport>({
		center: [-3.7038, 40.4168],
		zoom: 12,
		bearing: 0,
		pitch: 0
	});

	function clampZoom(next: MapViewport) {
		viewport = { ...next, zoom: Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, next.zoom)) };
	}
</script>

<div class="relative size-full">
	<Map class="size-full" {viewport} onviewportchange={clampZoom} />
	<p
		class="absolute top-3 left-3 rounded-md bg-background/90 px-2 py-1 font-mono text-xs shadow"
		aria-live="polite"
	>
		Zoom {viewport.zoom.toFixed(1)} (kept between {MIN_ZOOM} and {MAX_ZOOM})
	</p>
</div>

Globe

Set projection="globe" to draw the world as a sphere at low zoom. It flattens into the usual map as you zoom in, and stays a globe through theme and basemap swaps. Change it back to mercator at any time. Leave projection out and the map uses whatever projection the style sets.

<Map
	class="h-96"
	projection="globe"
	viewport={{ center: [0, 20], zoom: 1.5, bearing: 0, pitch: 0 }}
/>

Loading and errors

The root element has a data-status attribute: checking, loading, ready, error or unsupported.

  • While loading, a spinner shows. Pass a loader snippet to replace it.
  • onload runs once with the MapLibre map when the first style has loaded.
  • onerror gets style, tile and source errors. Without it, errors are logged to the console. If loading fails, the map shows a short message.
  • Browsers without WebGL 2 see a message instead of the map. Pass an unsupported snippet to replace it.
<Map class="h-96" onload={(map) => map.resize()} onerror={(error) => console.warn(error)}>
	{#snippet loader()}
		<p class="text-sm text-muted-foreground">Loading map…</p>
	{/snippet}
	{#snippet unsupported()}
		<p>Your browser cannot show this map.</p>
	{/snippet}
</Map>

options passes extra MapLibre options, such as maxZoom. workerUrl points at your own copy of the MapLibre worker. Both are read once, when the map is created. Bind ref to get the MapLibre map instance.

Keyboard

The map is a region named “Map” by default. Set aria-label to name it better. With focus on the map, arrow keys pan, plus and minus zoom, and Shift with the arrow keys rotates. A hidden hint tells screen reader users this.

Building your own child components

A component placed inside <Map> can call getMapContext() to reach the map. It throws outside a map.

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

	const ctx = getMapContext();
</script>

<button onclick={() => ctx.flyTo({ center: [13.405, 52.52], zoom: 14 })}>Go to Berlin</button>

The context gives you:

  • map: the MapLibre map, or null until it exists. maplibre is the loaded MapLibre module.
  • styleVersion: goes up on every style load. Read it in an effect to re-add anything you put on the style yourself.
  • colors: the shadcn theme colours, resolved to values MapLibre can use. They update when the theme changes.
  • flyTo, easeTo, fitBounds, zoomIn and zoomOut: camera moves that skip the animation when the user prefers reduced motion.
  • beforeRemove(callback): runs callback just before the map is removed, while its style is still there.

API Reference

Map

Props

NameTypeDescription
mapStyle MapStyleStyle URL or object, or `{ light, dark }` to follow the theme. Defaults to OpenFreeMap. Defaults to DEFAULT_MAP_STYLE.
viewport bindableMapViewportCamera. Bind it, or pass it with `onviewportchange` to control the camera fully.
projection MapProjection`globe` draws the world as a sphere at low zoom; it flattens as you zoom in. Leave it out to use the style's own projection, which is `mercator` for most styles.
options MapOptionsInputExtra MapLibre options, read once when the map is created.
workerUrl stringURL of the MapLibre worker. Defaults to the copy bundled with your app.
ref bindableMapLibreMap | nullThe MapLibre map instance. Defaults to null.

Events

NameTypeDescription
onviewportchange (viewport: MapViewport) => voidCalled with every proposed camera change. The map then shows whatever `viewport` holds.
onload (map: MapLibreMap) => voidCalled once with the map when its first style has loaded.
onerror (error: Error) => voidStyle, tile and source errors. Without it, errors are logged to the console.

Snippets

NameTypeDescription
loader SnippetShown while the map loads.
unsupported SnippetShown instead of the map when the browser has no WebGL 2.
children Snippet

Other attributes go to the underlying <div>.

Content Security Policy Control Container

On This Page

UsageStyleCameraGlobeLoading and errorsKeyboardBuilding your own child componentsAPI Reference

Handcrafted by Oggy. The source code is on GitHub.