MapSnippets logo MapSnippets logo

Drawing Tools with Leaflet

Leaflet

Draw, edit, and delete shapes on a Leaflet map with the Leaflet.draw plugin, using L.Control.Draw and an L.FeatureGroup to store them.

progress_activity Loading map...
const map = L.map('map').setView([51.5074, -0.1278], 13);
L.tileLayer('https://api.maptiler.com/maps/streets-v4/256/{z}/{x}/{y}.png?key=YOUR_MAPTILER_KEY', {
  tileSize: 256,
  attribution: '&copy; <a href="https://www.maptiler.com/">MapTiler</a> &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap contributors</a>'
}).addTo(map);
const drawnItems = new L.FeatureGroup();
map.addLayer(drawnItems);
const drawControl = new L.Control.Draw({
  edit: { featureGroup: drawnItems },
  draw: { polygon: true, polyline: true, rectangle: true, circle: true, marker: true }
});
map.addControl(drawControl);
map.on(L.Draw.Event.CREATED, (e) => {
  drawnItems.addLayer(e.layer);
});

How to draw and edit shapes in Leaflet

The Leaflet.draw plugin adds a toolbar for creating shapes interactively. A FeatureGroup stores all drawn shapes so they can be edited or deleted later. The L.Control.Draw constructor configures which drawing tools are available and links to the feature group for editing.

The L.Draw.Event.CREATED event fires when the user finishes drawing a shape. The event’s layer property contains the new shape, which must be added to the feature group manually. The edit toolbar lets users modify vertices or delete existing shapes.

Key APIs

API Description Docs
L.Control.Draw Drawing toolbar control github.com/Leaflet/Leaflet.draw
L.Draw.Event.CREATED Shape creation event github.com/Leaflet/Leaflet.draw
L.FeatureGroup Container for drawn layers leafletjs.com/reference.html#featuregroup

FAQ

How do I export drawn shapes as GeoJSON?

Call drawnItems.toGeoJSON() to get a GeoJSON FeatureCollection of all drawn shapes.

How do I disable specific drawing tools?

Set the tool to false in the draw options: { draw: { circle: false, marker: false } }.

Common mistakes

  • Forgetting to add the drawn layer to drawnItems in the CREATED handler, so shapes appear but cannot be edited or deleted
  • Not including leaflet.draw.css, which leaves the toolbar buttons unstyled and misaligned
  • Loading leaflet-draw.js before leaflet.js. The plugin needs Leaflet to load first.

Build maps using Leaflet with AI

Generate code like this drawing tools with leaflet example using the Leaflet skill in your IDE.