shadcn-svelte map
DocsComponentsBlocks
All blocks

Plot mapper

Editing

Trace fields over registry parcels, pick a crop for each and total the hectares.

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

Fields

0.0 ha mapped

Trace a field with the polygon, rectangle or freehand tool.

Install

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

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

Code

<script lang="ts">
	import SproutIcon from '@lucide/svelte/icons/sprout';
	import { cn } from '$lib/utils.js';
	import * as Card from '$lib/components/ui/card/index.js';
	import * as NativeSelect from '$lib/components/ui/native-select/index.js';
	import {
		Map,
		MapControlContainer,
		MapGeoJSON,
		MapScaleControl,
		MapZoomControl,
		pointInPolygon,
		polygonArea,
		ringCenter,
		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 { CROPS, PARCELS, VIEWPORT, type Crop } from './data.js';

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

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

	interface Field {
		key: string;
		label: string;
		crop: Crop;
		hectares: number;
		parcel: string | null;
	}

	const FIELD_MODES = ['polygon', 'rectangle', 'freehand'] as const;
	const SQUARE_METRES_PER_HECTARE = 10_000;
	const DEFAULT_CROP: Crop = 'Wheat';

	let tool = $state<DrawTool>('none');
	let drawings = $state.raw<DrawFeature[]>([]);
	// Crops are kept by drawing id and never pruned, so an undone delete gets its crop back.
	let crops = $state.raw<Record<string, Crop>>({});
	let hoveredParcel = $state<string | null>(null);

	interface ParcelEntry {
		name: string;
		rings: LngLatTuple[][];
		west: number;
		south: number;
		east: number;
		north: number;
	}

	// Parcels never change, so their bounds are worked out once. A field's centre is
	// only tested against the polygons of parcels whose bounds contain it.
	const parcelIndex: ParcelEntry[] = PARCELS.features.map((parcel) => {
		const rings = parcel.geometry.coordinates as LngLatTuple[][];
		const lngs = rings[0].map(([lng]) => lng);
		const lats = rings[0].map(([, lat]) => lat);
		return {
			name: parcel.properties.name,
			rings,
			west: Math.min(...lngs),
			south: Math.min(...lats),
			east: Math.max(...lngs),
			north: Math.max(...lats)
		};
	});

	function parcelAt(point: LngLatTuple): string | null {
		const [lng, lat] = point;
		const found = parcelIndex.find(
			(parcel) =>
				lng >= parcel.west &&
				lng <= parcel.east &&
				lat >= parcel.south &&
				lat <= parcel.north &&
				pointInPolygon(point, parcel.rings)
		);
		return found?.name ?? null;
	}

	const fields: Field[] = $derived(
		drawings.flatMap((feature, index): Field[] => {
			if (feature.geometry.type !== 'Polygon') return [];
			const key = String(feature.id);
			const rings = feature.geometry.coordinates as LngLatTuple[][];
			return [
				{
					key,
					label: `Field ${index + 1}`,
					crop: crops[key] ?? DEFAULT_CROP,
					hectares: polygonArea(rings) / SQUARE_METRES_PER_HECTARE,
					parcel: parcelAt(ringCenter(rings[0]))
				}
			];
		})
	);

	const totals = $derived.by(() => {
		// One pass over the fields, then crops in their usual order.
		const byCrop = fields.reduce<Partial<Record<Crop, number>>>(
			(sums, field) => ({ ...sums, [field.crop]: (sums[field.crop] ?? 0) + field.hectares }),
			{}
		);
		return CROPS.flatMap((crop) => {
			const hectares = byCrop[crop] ?? 0;
			return hectares > 0 ? [{ crop, hectares }] : [];
		});
	});

	const totalHectares = $derived(fields.reduce((sum, field) => sum + field.hectares, 0));
</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="Field map"
		{mapStyle}
		viewport={VIEWPORT}
	>
		<MapGeoJSON
			id="plot-parcels"
			data={PARCELS}
			fillOpacity={0.04}
			hoverFillOpacity={0.12}
			lineWidth={1}
			onhover={(feature) => (hoveredParcel = feature ? String(feature.properties.name) : null)}
		/>
		<MapControlContainer position="top-left">
			<MapDrawControl
				orientation="horizontal"
				modes={FIELD_MODES}
				bind:mode={tool}
				onchange={(features) => (drawings = features)}
			/>
		</MapControlContainer>
		<MapControlContainer position="top-right">
			<MapZoomControl />
		</MapControlContainer>
		<MapControlContainer position="bottom-left">
			<MapScaleControl />
		</MapControlContainer>
	</Map>

	<Card.Root class="min-h-0 gap-4 overflow-y-auto">
		<Card.Header>
			<Card.Title>Fields</Card.Title>
			<Card.Description aria-live="polite">
				{hoveredParcel ?? `${totalHectares.toFixed(1)} ha mapped`}
			</Card.Description>
		</Card.Header>
		<Card.Content class="flex flex-col gap-4">
			{#if totals.length > 0}
				<dl class="grid grid-cols-2 gap-x-4 gap-y-1 text-sm" data-testid="crop-totals">
					{#each totals as total (total.crop)}
						<dt class="text-muted-foreground">{total.crop}</dt>
						<dd class="text-right tabular-nums">{total.hectares.toFixed(1)} ha</dd>
					{/each}
				</dl>
			{/if}
			{#each fields as field (field.key)}
				<div class="flex flex-col gap-2 rounded-md border p-3" data-testid="field">
					<div class="flex items-center justify-between text-sm">
						<span class="font-medium">{field.label}</span>
						<span class="text-muted-foreground tabular-nums">{field.hectares.toFixed(2)} ha</span>
					</div>
					<p class="text-xs text-muted-foreground">{field.parcel ?? 'Outside the registry'}</p>
					<NativeSelect.Root
						class="w-full"
						size="sm"
						aria-label="Crop of {field.label}"
						value={field.crop}
						onchange={(event) =>
							(crops = { ...crops, [field.key]: event.currentTarget.value as Crop })}
					>
						{#each CROPS as crop (crop)}
							<NativeSelect.Option value={crop}>{crop}</NativeSelect.Option>
						{/each}
					</NativeSelect.Root>
				</div>
			{:else}
				<div
					class="flex flex-col items-center gap-2 py-6 text-center text-sm text-muted-foreground"
				>
					<SproutIcon class="size-5" />
					<p>Trace a field with the polygon, rectangle or freehand tool.</p>
				</div>
			{/each}
		</Card.Content>
	</Card.Root>
</div>
import type { FeatureCollection, Polygon } from 'geojson';
import type { LngLatTuple, MapViewport } from '$lib/components/ui/map/index.js';

/** Farmland outside a village; parcels are the land registry boundaries. */
export const VIEWPORT: MapViewport = {
	center: [8.612, 52.912],
	zoom: 14.2,
	bearing: 0,
	pitch: 0
};

export const CROPS = ['Wheat', 'Barley', 'Maize', 'Rapeseed', 'Grassland', 'Fallow'] as const;

export type Crop = (typeof CROPS)[number];

function parcel(name: string, ring: LngLatTuple[]) {
	const geometry: Polygon = { type: 'Polygon', coordinates: [[...ring, ring[0]]] };
	return { type: 'Feature' as const, properties: { name }, geometry };
}

/** Registry parcels shown for reference. Fields are drawn on top of them. */
export const PARCELS: FeatureCollection<Polygon, { name: string }> = {
	type: 'FeatureCollection',
	features: [
		parcel('Parcel 112', [
			[8.598, 52.915],
			[8.607, 52.9158],
			[8.6078, 52.9105],
			[8.5985, 52.9098]
		]),
		parcel('Parcel 113', [
			[8.6085, 52.916],
			[8.6195, 52.9168],
			[8.62, 52.9112],
			[8.609, 52.9106]
		]),
		parcel('Parcel 118', [
			[8.599, 52.909],
			[8.6075, 52.9097],
			[8.608, 52.9045],
			[8.5995, 52.904]
		]),
		parcel('Parcel 119', [
			[8.6088, 52.9098],
			[8.6265, 52.9105],
			[8.6268, 52.905],
			[8.6092, 52.9046]
		])
	]
};

Handcrafted by Oggy. The source code is on GitHub.