import {
Map,
MapDrawCircle,
MapDrawControl,
MapDrawDelete,
MapDrawEdit,
MapDrawMarker,
MapDrawPolygon,
MapDrawPolyline,
MapDrawRectangle,
MapTileLayer,
} from "@/components/ui/map"
import type { LatLngExpression } from "leaflet"
export function MapWithDrawControl() {
const TORONTO_COORDINATES = [43.6532, -79.3832] satisfies LatLngExpression
return (
<Map center={TORONTO_COORDINATES}>
<MapTileLayer />
<MapDrawControl>
<MapDrawMarker />
<MapDrawPolyline />
<MapDrawCircle />
<MapDrawRectangle />
<MapDrawPolygon />
<MapDrawEdit />
<MapDrawDelete />
</MapDrawControl>
</Map>
)
}
Accessing Drawn Shapes
You can pass an optional onLayersChange
callback to the draw control to get the current layers on the map.
This allows you to handle the drawn shapes, such as saving their coordinates or performing further actions.
"use client"
import { Badge } from "@/components/ui/badge"
import {
Map,
MapDrawCircle,
MapDrawControl,
MapDrawDelete,
MapDrawEdit,
MapDrawMarker,
MapDrawPolygon,
MapDrawPolyline,
MapDrawRectangle,
MapTileLayer,
useLeaflet,
} from "@/components/ui/map"
import type { LatLngExpression } from "leaflet"
import { useState } from "react"
export function MapWithDrawControlCallback() {
const TORONTO_COORDINATES = [43.6532, -79.3832] satisfies LatLngExpression
const { L } = useLeaflet()
const [numberOfShapes, setNumberOfShapes] = useState(0)
return L ? (
<Map center={TORONTO_COORDINATES}>
<MapTileLayer />
<MapDrawControl
onLayersChange={(layers) => {
setNumberOfShapes(layers.getLayers().length)
layers.eachLayer((layer) => {
if (layer instanceof L.Marker) {
console.log("Marker:", layer.getLatLng())
} else if (
layer instanceof L.Polyline &&
!(layer instanceof L.Polygon)
) {
console.log("Polyline:", layer.getLatLngs())
} else if (layer instanceof L.Circle) {
console.log(
"Circle center:",
layer.getLatLng(),
"radius:",
layer.getRadius()
)
} else if (layer instanceof L.Rectangle) {
console.log("Rectangle bounds:", layer.getBounds())
} else if (layer instanceof L.Polygon) {
console.log("Polygon:", layer.getLatLngs())
}
})
}}>
<MapDrawMarker />
<MapDrawPolyline />
<MapDrawCircle />
<MapDrawRectangle />
<MapDrawPolygon />
<MapDrawEdit />
<MapDrawDelete />
</MapDrawControl>
<Badge className="absolute right-1 bottom-1 z-1000">
Shapes: {numberOfShapes}
</Badge>
</Map>
) : null
}
Using Specific Shapes
Simply include only the shape controls you want inside MapDrawControl
.
import {
Map,
MapDrawCircle,
MapDrawControl,
MapDrawEdit,
MapDrawPolygon,
MapDrawRectangle,
MapTileLayer,
} from "@/components/ui/map"
import type { LatLngExpression } from "leaflet"
export function MapWithDrawControlSpecificShapes() {
const TORONTO_COORDINATES = [43.6532, -79.3832] satisfies LatLngExpression
return (
<Map center={TORONTO_COORDINATES}>
<MapTileLayer />
<MapDrawControl>
<MapDrawCircle />
<MapDrawRectangle />
<MapDrawPolygon />
<MapDrawEdit />
</MapDrawControl>
</Map>
)
}