Drawing, Editing, and Measuring on Maps
🎯 Introduction
By the end of this article, you will be able to design drawing and editing workflows, save results as GeoJSON, and measure distances and areas.
🧱 Where drawing tools come from
Mapbox GL JS handles rendering and events but does not include a complete vertex editor. Applications typically integrate a drawing tool such as Mapbox GL Draw and use Turf for distance and area calculations.
The examples use Node.js 22.9.0, mapbox-gl@3.14.0, @mapbox/mapbox-gl-draw@1.5.0, and @turf/turf@7.2.0:
pnpm add @mapbox/mapbox-gl-draw@1.5.0 @turf/turf@7.2.0
import MapboxDraw from '@mapbox/mapbox-gl-draw'
import '@mapbox/mapbox-gl-draw/dist/mapbox-gl-draw.css'
const draw = new MapboxDraw({
displayControlsDefault: false,
controls: {
point: true,
line_string: true,
polygon: true,
trash: true,
},
})
map.addControl(draw, 'top-right')
Point, LineString, and Polygon represent locations, paths, and enclosed areas. The tool provides basic drawing, selection, vertex movement, and geometry deletion.
✏️ Switch between drawing and editing
Purpose: let users create points, lines, and polygons, then change their locations or shapes.
draw.changeMode('draw_point')
draw.changeMode('draw_line_string')
draw.changeMode('draw_polygon')
draw.changeMode('simple_select')
draw.changeMode('direct_select', { featureId })
draw.trash()
simple_select selects and moves entire features; direct_select edits an individual feature's vertices. Clearly display the current mode and leave editing mode after saving or canceling.
Try drawing and editing below: choose “Draw point”, “Draw line”, or “Draw polygon”, then interact with the map. Double-click to finish lines and polygons. Return to “Select / Edit”, select a line or polygon, then click it again. When white vertices appear, drag them to reshape the feature.
Double-click to finish a line or polygon. To reshape it, select it, click it again, and drag the white vertices.
The current mode and feature count appear below the component. After drawing a line or polygon, switch to “Select / Edit” and click the feature again to expose its draggable white vertices.
🔔 Track, save, and validate GeoJSON
Purpose: keep the latest map draft available and handle save and cancel actions correctly.
let draftGeoJSON = draw.getAll()
let originalGeoJSON = structuredClone(draftGeoJSON)
function syncDraft() {
draftGeoJSON = draw.getAll()
}
map.on('draw.create', syncDraft)
map.on('draw.update', syncDraft)
map.on('draw.delete', syncDraft)
async function saveDraft() {
validate(draftGeoJSON)
await saveGeometry(draftGeoJSON)
originalGeoJSON = structuredClone(draftGeoJSON)
draw.changeMode('simple_select')
}
function cancelEdit() {
draw.set(originalGeoJSON)
draw.changeMode('simple_select')
}
draftGeoJSON stores the current draft, originalGeoJSON stores the data from before editing, and saveGeometry represents your application's save API. To edit existing data, fetch its GeoJSON and call draw.set(featureCollection). Update the original copy after a successful save. On cancel, restore that copy with draw.set rather than retaining the modified data.
Validate the draft before submitting: Points need valid longitude and latitude, LineStrings need at least two distinct coordinates, and Polygons must form valid enclosed areas. Disable the save button while a request is in progress to prevent duplicate submissions.
📏 Measure distance and area
Purpose: calculate distances from drawn paths and areas from enclosed regions.
import { area, length } from '@turf/turf'
const kilometers = length(lineFeature, { units: 'kilometers' })
const squareMeters = area(polygonFeature)
const distanceLabel = `${kilometers.toFixed(2)} km`
const areaLabel = `${Math.round(squareMeters)} ㎡`
For distance, draw a LineString, calculate its length on change events, and update the result label. For area, draw a Polygon, calculate its area, display units, and allow redrawing. Format interface values to the application's required precision while retaining the original geometry for submission.
Choose “Measure distance” or “Measure area” below, click successive points on the map, and double-click to finish. The result appears immediately above the map.
🧾 Summary
- Mapbox GL JS does not include a complete vertex editor; applications typically integrate a drawing tool.
- Drawing modes create geometry; selection modes move features or edit vertices.
- Use
draw.create,draw.update, anddraw.deleteto synchronize drafts. - Save drawing results as GeoJSON and load existing data for further editing.
- Turf calculates distances and areas from LineStrings and Polygons.
- Before saving, validate geometry and allowed extents, and check duplicate submissions and version conflicts.
❓ Questions and answers
Q1: Why not write edits directly into list data?
Users may cancel. Keeping both an original copy and a draft makes reliable restoration possible.
Q2: Why round the area result?
Measurements often produce long decimal values. Format them to the required precision rather than showing meaningless digits.
Q3: Can drawing tool output be submitted directly?
First validate geometry types, coordinate counts, allowed extents, and application fields.
🧪 Exercises
- Design state for starting, saving, and canceling edits, including restoration on cancel.
- Listen for line updates, calculate distance, and display two decimal places.
// Write your code here
🎉 You now know how to build drawing, editing, and measurement workflows!
