Drawing and editing geometry
Quick answer
Leaflet core ships no drawing tools, so this tutorial builds a small state machine on top of map click events. It shows how to collect e.latlng into an array, refresh an L.polygon with setLatLngs, and place draggable L.marker vertices using L.divIcon. It also covers finishing on dblclick with doubleClickZoom disabled, computing spherical ring area, and removing every vertex marker on cancel. Readers can implement a lightweight editor without a plugin.
Key points
- Push e.latlng on map click and rebuild geometry with L.polygon or polyline.setLatLngs.
- Represent vertices as draggable L.marker instances with L.divIcon and update on the drag event.
- Disable doubleClickZoom and drop the duplicated last vertex when dblclick finishes the shape.
Example
var dot = L.divIcon({
className: '',
html: '<div class="vertex"></div>',
iconSize: [10, 10],
iconAnchor: [5, 5]
});
var vertex = L.marker(latlng, { icon: dot, draggable: true })
.on('drag', function (e) {
points[index] = e.target.getLatLng();
polygon.setLatLngs(points);
refreshArea();
})
.addTo(map);var map = L.map('map', {
center: [39.907359, 116.391263],
zoom: 12,
doubleClickZoom: false
});
map.on('dblclick', function () {
if (points.length > 1) {
var last = points[points.length - 1];
var prev = points[points.length - 2];
if (last.distanceTo(prev) < 1) {
points.pop();
vertexGroup.removeLayer(vertexGroup.getLayers().pop());
}
}
if (points.length >= 3) finish();
});
Notes
- A double click fires two click events first, so the final vertex is added twice unless handled.
- dragend updates only when the finger lifts; use drag so the outline follows the pointer.
English edition written for Atlaslog. Code is taken from the original Chinese page and runs unchanged.
Atlaslog (2026). Drawing and editing geometry. https://www.jingweizhi.com/en/leaflet/tutorials/draw-edit.html (accessed 2026-11-03).