<script lang="ts">
import { Map, MapControlContainer, lineLength, polygonArea } from '$lib/components/ui/map/index.js';
import {
MapDrawControl,
type DrawFeature,
type DrawTool
} from '$lib/components/ui/map-draw/index.js';
let tool = $state<DrawTool>('none');
let drawings = $state.raw<DrawFeature[]>([]);
const SQUARE_METRES_PER_HECTARE = 10_000;
const METRES_PER_KILOMETRE = 1000;
function measure(feature: DrawFeature): string {
const geometry = feature.geometry;
if (geometry.type === 'Polygon') {
const hectares =
polygonArea(geometry.coordinates as [number, number][][]) / SQUARE_METRES_PER_HECTARE;
return `${hectares.toFixed(1)} ha`;
}
if (geometry.type === 'LineString') {
const km = lineLength(geometry.coordinates as [number, number][]) / METRES_PER_KILOMETRE;
return `${km.toFixed(2)} km`;
}
return 'point';
}
</script>
<div class="relative size-full">
<Map
class="size-full"
viewport={{ center: [-122.4194, 37.7749], zoom: 12.5, bearing: 0, pitch: 0 }}
>
<MapControlContainer position="top-left">
<MapDrawControl bind:mode={tool} onchange={(features) => (drawings = features)} />
</MapControlContainer>
</Map>
<div
class="absolute top-2 right-2 w-44 rounded-md border bg-background/95 p-2 text-xs shadow-sm"
aria-live="polite"
>
{#if drawings.length === 0}
<p class="text-muted-foreground">Pick a tool and draw on the map.</p>
{:else}
<ul class="flex flex-col gap-1">
{#each drawings as feature (feature.id)}
<li class="flex justify-between gap-2">
<span class="capitalize">{feature.properties.mode}</span>
<span class="font-mono tabular-nums">{measure(feature)}</span>
</li>
{/each}
</ul>
{/if}
</div>
</div>
The Draw Control adds a toolbar to the map. It is built on terra-draw and ships as its own item, so add it next to the map:
pnpm dlx shadcn-svelte@latest add https://shadcn-svelte-map.vercel.app/r/map-draw.jsonnpx shadcn-svelte@latest add https://shadcn-svelte-map.vercel.app/r/map-draw.jsonyarn dlx shadcn-svelte@latest add https://shadcn-svelte-map.vercel.app/r/map-draw.jsonbunx --bun shadcn-svelte@latest add https://shadcn-svelte-map.vercel.app/r/map-draw.jsonTools
| Tool | How to draw |
|---|---|
point | Click to place a point. |
polyline | Click to add points. Click the last point again, or press Enter, to finish. |
polygon | Click to add corners. Click the first corner, or press Enter, to close it. |
rectangle | Click one corner, then the opposite corner. |
circle | Click the centre, then click again at the radius you want. |
freehand | Click to start, move the pointer, click again to finish. |
select | Click a shape to edit it. Drag to move it, drag corners to reshape it. |
Escape cancels the shape you are drawing. The toolbar also has delete, undo and redo buttons. Undo and redo cover every step of the session: creating, moving, reshaping and deleting.
Show fewer tools with modes, in the order you want:
<MapDrawControl modes={['polygon', 'rectangle']} />Getting the drawings
onchange gives you every finished drawing after each change. It skips the shape being drawn and the editing handles, so you only ever see complete features:
<script lang="ts">
import { Map, MapControlContainer } from '$lib/components/ui/map/index.js';
import { MapDrawControl, type DrawFeature } from '$lib/components/ui/map-draw/index.js';
let drawings = $state.raw<DrawFeature[]>([]);
</script>
<Map class="h-96">
<MapControlContainer position="top-left">
<MapDrawControl onchange={(features) => (drawings = features)} />
</MapControlContainer>
</Map>Each DrawFeature is plain GeoJSON: a Point, LineString or Polygon, with properties.mode telling you which tool drew it. Rectangles and circles arrive as polygons. Save the array as it is, or wrap it in a FeatureCollection.
Controlling the tool
Bind mode to read or set the active tool from your own UI. none hands the pointer back to the map, so it pans and zooms again.
<script lang="ts">
import type { DrawTool } from '$lib/components/ui/map-draw/index.js';
let tool = $state<DrawTool>('none');
</script>
<MapDrawControl bind:mode={tool} />
<button onclick={() => (tool = 'polygon')}>Draw a zone</button>Keeping details per drawing
Each feature has a stable id. Store names, notes or prices in a record keyed by that id, rather than inside the feature. Keep entries when a drawing disappears, so undo brings the details back with it. The geofence editor and plot mapper blocks work this way.
Measuring
The map exports geometry helpers that work on drawings directly. polygonArea returns square metres and lineLength returns metres. See Utilities.
Loading saved drawings
Pass saved drawings to features and they load when the toolbar starts, ready to select and edit. Bind it to keep your list in step with every change:
<script lang="ts">
import { MapDrawControl, type DrawFeature } from '$lib/components/ui/map-draw/index.js';
let { saved }: { saved: DrawFeature[] } = $props();
let drawings = $state.raw(saved);
</script>
<MapDrawControl bind:features={drawings} />Give features a different list, such as another user’s zones, and it replaces what is on the map. Passing back the list the control reported changes nothing, so undo history is kept. Loading is not a step people can undo.
Saved features keep their ids, so ids from your database work as they are. A feature that cannot be drawn, such as a point marked polygon, is left out and reported through onerror; onchange then reports the list without it.