shadcn-svelte map
DocsComponentsBlocks
All blocks

Geofence editor

Editing

Draw fences around a harbour and see which assets sit inside them.

Use the arrow keys to pan, plus and minus to zoom, and Shift with the arrow keys to rotate.

Geofences

1 of 6 assets inside a fence

36.7 ha 1 inside

Install

Adds the block to src/lib/components/geofence-editor and the map if you do not have it yet.

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

Code

<script lang="ts">
	import ShieldIcon from '@lucide/svelte/icons/shield';
	import { cn } from '$lib/utils.js';
	import { Badge } from '$lib/components/ui/badge/index.js';
	import * as Card from '$lib/components/ui/card/index.js';
	import { Input } from '$lib/components/ui/input/index.js';
	import {
		Map,
		MapControlContainer,
		MapMarker,
		MapMarkerContent,
		MapMarkerTooltip,
		MapZoomControl,
		pointInPolygon,
		polygonArea,
		type LngLatTuple,
		type MapStyle
	} from '$lib/components/ui/map/index.js';
	import {
		MapDrawControl,
		type DrawFeature,
		type DrawTool
	} from '$lib/components/ui/map-draw/index.js';
	import { ASSETS, SAVED_FENCES, SAVED_NAMES, VIEWPORT } from './data.js';

	interface Props {
		/** Basemap. Defaults to OpenFreeMap. */
		mapStyle?: MapStyle;
		class?: string;
	}

	let { mapStyle, class: className }: Props = $props();

	interface Fence {
		key: string;
		name: string;
		area: number;
		inside: string[];
	}

	const FENCE_MODES = ['polygon', 'rectangle', 'circle'] as const;
	const SQUARE_METRES_PER_HECTARE = 10_000;
	const SQUARE_METRES_PER_KM2 = 1_000_000;

	let tool = $state<DrawTool>('none');
	let drawings = $state.raw<DrawFeature[]>(SAVED_FENCES);
	// Names are kept by feature id and never pruned, so undoing a delete brings the name back.
	let names = $state.raw<Record<string, string>>(SAVED_NAMES);

	const fences: Fence[] = $derived(
		drawings.flatMap((feature, index): Fence[] => {
			if (feature.geometry.type !== 'Polygon') return [];
			const key = String(feature.id);
			const rings = feature.geometry.coordinates as LngLatTuple[][];
			const inside = ASSETS.filter((asset) => pointInPolygon(asset.lngLat, rings));
			return [
				{
					key,
					name: names[key] ?? `Fence ${index + 1}`,
					area: polygonArea(rings),
					inside: inside.map((asset) => asset.id)
				}
			];
		})
	);

	// Looked up by asset id; an asset inside two fences counts once.
	const fenced: Record<string, true> = $derived(
		Object.fromEntries(fences.flatMap((fence) => fence.inside.map((id) => [id, true] as const)))
	);

	const fencedCount = $derived(Object.keys(fenced).length);

	function formatArea(squareMetres: number): string {
		if (squareMetres >= SQUARE_METRES_PER_KM2) {
			return `${(squareMetres / SQUARE_METRES_PER_KM2).toFixed(2)} km²`;
		}
		return `${(squareMetres / SQUARE_METRES_PER_HECTARE).toFixed(1)} ha`;
	}

	function rename(key: string, value: string) {
		names = { ...names, [key]: value };
	}
</script>

<div class={cn('grid min-h-[560px] gap-4 p-4 lg:grid-cols-[minmax(0,1fr)_20rem]', className)}>
	<Map
		class="min-h-[360px] rounded-lg border"
		aria-label="Geofence map"
		{mapStyle}
		viewport={VIEWPORT}
	>
		{#each ASSETS as asset (asset.id)}
			{@const isFenced = fenced[asset.id] === true}
			<MapMarker lngLat={asset.lngLat} aria-label="{asset.name}, {isFenced ? 'inside' : 'outside'}">
				<MapMarkerContent>
					<span
						class={[
							'block size-3.5 rounded-full border-2 border-background shadow',
							isFenced ? 'bg-primary' : 'bg-muted-foreground'
						]}
						data-testid="asset-{asset.id}"
						data-fenced={isFenced}
					></span>
				</MapMarkerContent>
				<MapMarkerTooltip>{asset.name}</MapMarkerTooltip>
			</MapMarker>
		{/each}

		<MapControlContainer position="top-left">
			<MapDrawControl
				orientation="horizontal"
				modes={FENCE_MODES}
				bind:mode={tool}
				bind:features={drawings}
			/>
		</MapControlContainer>
		<MapControlContainer position="top-right">
			<MapZoomControl />
		</MapControlContainer>
	</Map>

	<Card.Root class="min-h-0 gap-4 overflow-y-auto">
		<Card.Header>
			<Card.Title>Geofences</Card.Title>
			<Card.Description data-testid="fence-summary">
				{fencedCount} of {ASSETS.length} assets inside a fence
			</Card.Description>
		</Card.Header>
		<Card.Content class="flex flex-col gap-3">
			{#each fences as fence (fence.key)}
				<div class="flex flex-col gap-2 rounded-md border p-3" data-testid="fence">
					<Input
						value={fence.name}
						aria-label="Fence name"
						oninput={(event) => rename(fence.key, event.currentTarget.value)}
					/>
					<div class="flex items-center justify-between text-sm text-muted-foreground">
						<span>{formatArea(fence.area)}</span>
						<Badge variant={fence.inside.length > 0 ? 'default' : 'secondary'}>
							{fence.inside.length} inside
						</Badge>
					</div>
				</div>
			{:else}
				<div
					class="flex flex-col items-center gap-2 py-6 text-center text-sm text-muted-foreground"
				>
					<ShieldIcon class="size-5" />
					<p>Pick a shape on the map and draw a fence around your assets.</p>
				</div>
			{/each}
		</Card.Content>
	</Card.Root>
</div>
import type { LngLatTuple, MapViewport } from '$lib/components/ui/map/index.js';
import type { DrawFeature } from '$lib/components/ui/map-draw/index.js';

export interface Asset {
	id: string;
	name: string;
	lngLat: LngLatTuple;
}

/** Hamburg harbour, where the sample assets are parked. */
export const VIEWPORT: MapViewport = {
	center: [9.955, 53.536],
	zoom: 12.6,
	bearing: 0,
	pitch: 0
};

export const ASSETS: Asset[] = [
	{ id: 'truck-1', name: 'Truck 1', lngLat: [9.9312, 53.5396] },
	{ id: 'truck-2', name: 'Truck 2', lngLat: [9.9458, 53.5331] },
	{ id: 'truck-3', name: 'Truck 3', lngLat: [9.9634, 53.5402] },
	{ id: 'crane-1', name: 'Crane 1', lngLat: [9.9721, 53.5298] },
	{ id: 'crane-2', name: 'Crane 2', lngLat: [9.9533, 53.5263] },
	{ id: 'van-1', name: 'Van 1', lngLat: [9.9805, 53.5427] }
];

/** A fence saved earlier, loaded into the draw control so it can be edited. */
export const SAVED_FENCES: DrawFeature[] = [
	{
		type: 'Feature',
		id: 'container-yard',
		geometry: {
			type: 'Polygon',
			coordinates: [
				[
					[9.926, 53.537],
					[9.936, 53.537],
					[9.936, 53.542],
					[9.926, 53.542],
					[9.926, 53.537]
				]
			]
		},
		properties: { mode: 'rectangle' }
	}
];

export const SAVED_NAMES: Record<string, string> = { 'container-yard': 'Container yard' };

Handcrafted by Oggy. The source code is on GitHub.