A GIS editor asks a lot of a map. People need to inspect features, change boundaries, edit attributes, and recover from a mistake without losing their work.
We built the Geoman GIS workspace to show how that can feel inside an application. It has layers, a legend, a feature inspector, geometry tools, undo/redo, and a live event console. MapLibre renders the map; MapLibre-Geoman Pro handles geometry editing; our application connects the controls and manages the project.
This guide walks through the choices behind it, including a few details that took care to get right: editing one feature at a time, cancelling a split, moving individual polygon parts, and rejecting a hole snapped onto its own boundary.
Try the workspace or download the runnable Vite starter. The starter's controller is covered by browser tests, and the longer code excerpts below come directly from that source.
Versions: MapLibre-Geoman Pro 0.13.11 and MapLibre GL JS 6. You need Pro package access for the advanced tools. The public demo keeps edits in your browser; export GeoJSON to keep them. It has no database or collaboration service.
How the application fits together
We keep the interface, project data, and map integration separate:
- The workspace UI contains the layer tree, legend, inspector, toolbar and console.
- Application state holds clean GeoJSON, appearance, selection and edit history.
- A renderer adapter implements methods such as
select,setTool,getFeatures,replaceFeaturesandzoomTo. - Geoman and MapLibre provide the editing operations and map rendering.
The inspector calls the adapter rather than reaching into map sources. That gives us one place to handle map-specific behavior and lets the same interface work with Leaflet. The framework is incidental: we use Svelte, but the same structure works in React, Vue or plain JavaScript.
The dashed connection in the diagram shows where a production backend would fit. The demo runs without one.
Set up MapLibre and Geoman Pro
The starter uses Vite. Configure private-registry authentication according to your Pro subscription instructions before installing. Keep that token out of browser code and your repository.
npm create vite@latest my-gis-editor -- --template vanilla
cd my-gis-editor
npm install
npm install maplibre-gl@6 @geoman-io/[email protected]
npm run devImport both stylesheets and configure the MapLibre worker. Here is the initialization pattern used by the starter:
import { Map as MapLibreMap, setWorkerUrl } from "maplibre-gl"
import workerUrl from "maplibre-gl/dist/maplibre-gl-worker.mjs?worker&url"
import { Geoman } from "@geoman-io/maplibre-geoman-pro"
import "maplibre-gl/dist/maplibre-gl.css"
import "@geoman-io/maplibre-geoman-pro/dist/maplibre-geoman.css"
setWorkerUrl(workerUrl)
const map = new MapLibreMap({
container: "map",
center: [13.4, 52.52],
zoom: 14,
style: {
version: 8,
sources: {},
layers: [{ id: "background", type: "background" }],
},
})
const gm = new Geoman(map, {
settings: {
controlsUiEnabledByDefault: false,
validateGeometry: true,
history: { mode: "controlled" },
keyboard: { enabled: false },
},
})
await gm.waitForGeomanLoaded()This starts with a blank map that needs no basemap token. Supply your own licensed style for streets and labels, retaining its attribution.
We disable the built-in toolbar and shortcuts because the application supplies them. Controlled history lets the app manage its own undo stack. Geoman's built-in history is another option; choose one owner for history rather than maintaining two independent stacks over the same edits.
Give the map a container with a real height. In an SSR framework, initialize it after mount, call map.resize() when panels change its size, and destroy the engine on unmount. Those small lifecycle details prevent a surprising number of blank-map bugs.
Keep layers, attributes and styling in sync
Our fictional Berlin project contains planning zones, an access route and points of interest. Each feature has a stable ID, separate from its editable name and display code. Some zones have multiple polygon parts or holes; those parts share one set of attributes.
The full workspace uses three named data layers. The starter keeps one, parcels, to make the code easier to follow:
const parcelStyle = {
polygon: {
fillColor: {
categorical: {
field: "status",
categories: {
Planned: "#7663E9",
Approved: "#2D9B8A",
"In review": "#D99A35",
},
fallback: "#63758B",
},
},
fillOpacity: 0.25,
strokeColor: "#53677A",
strokeWidth: 2,
},
}
geoman.dataLayers.add({
id: "parcels",
name: "Planning zones",
editable: true,
style: parcelStyle,
})
await geoman.dataLayers.setData(
"parcels",
structuredClone(initialData.features),
)
geoman.dataLayers.setActive("parcels")In this version, setData() takes the feature array from the GeoJSON FeatureCollection. The map and legend read from the same appearance settings, so changing a status color updates both.
Clicking a legend swatch opens a small styling popover. Selection then uses a thicker, darker outline derived from that feature's color. An approved zone stays green when selected. We also draw a padded dotted bounding rectangle, so selection remains visible against a busy basemap.
The legend and attribute inspector are our UI components. Geoman provides the data-layer and styling APIs underneath them.
Separate selection from an editing session
Clicking a feature opens its inspector. Changing its geometry takes a separate action: Edit feature, the E shortcut, or a double-click.
Once editing starts, the guidance bar names the target, the layer row gets an editing indicator, and other features are protected. Done / Enter keeps the changes. Cancel / Escape restores the session's starting point.
While editing, users finish or cancel before choosing another feature or hiding its layer. On mobile, starting an edit closes the inspector to reveal the map. The inspector still has its own Cancel control if reopened.
This is a simplified GIS workflow, with familiar ideas from desktop and web editors. We are not trying to reproduce every part of QGIS, Felt or Atlas.
Make only the active feature editable
A highlighted polygon does not, by itself, restrict editing. The adapter temporarily sets disableEdit on other features, preserving and later restoring their original values:
async function lockOtherFeatures() {
await Promise.all(
getData().features.map(async ({ id }) => {
const feature = geoman.features.findEditableFeature(id)
if (!feature) return
if (!locks.has(id))
locks.set(id, feature.getShapeProperty("disableEdit"))
await feature.setShapeProperty(
"disableEdit",
id !== selectedId || locks.get(id) === true,
)
}),
)
}
async function restoreLocks() {
await Promise.all(
[...locks].map(async ([id, previous]) => {
const feature = geoman.features.findEditableFeature(id)
if (!feature) return
if (previous === undefined)
await feature.deleteShapeProperty("disableEdit")
else await feature.setShapeProperty("disableEdit", previous)
}),
)
locks.clear()
}Other features stay visible and remain available for snapping. We do not remove them from the map to protect them.
The same restriction applies to Move and Split. A split line can pass through a zone and a nearby access route, but only the active zone changes. The restriction belongs in the adapter as well as the interface.
These flags prevent accidental edits in the browser. Your backend still needs its own permissions checks.
Give Cancel something real to restore
At session start, we take a deep copy of the project data. The full workspace also saves its history array and history position. Tool changes within that session keep the same checkpoint.
That matters after a split. The original feature may be gone, replaced by children with new IDs. Putting back its old coordinates would leave those children behind. Cancel instead restores the data layer from the checkpoint, bringing back the original identity and removing the children. Restoring the history checkpoint also preserves any redo branch that existed before editing began.
The downloadable controller exposes this lifecycle:
// These methods belong to the starter controller, not the native Geoman API.
await editor.begin(featureId, "change")
await editor.setTool("drag") // Same session, different editing tool.
// When the user chooses Done:
const { before, after } = await editor.done()
// Or, when the user chooses Cancel:
await editor.cancel()The full showcase allows Undo within a session without going back before its starting point. Done keeps the accepted history steps. Invalid operations create no history entry.
Done accepts the local draft. If you add a backend, give saving its own state so a failed request does not look like a successful save.
Export complete GeoJSON during an edit
An active feature can temporarily leave its home source while Geoman edits it. Reading only that home source can omit the feature from an export.
Our reader includes the editable sources and the temporary source. It excludes unfinished drawings and strips reserved engine properties from this polygon-based project's domain data:
function getData() {
const collection = geoman.features.asGeoJsonFeatureCollection({
sourceNames: [
...new Set([...geoman.features.editableSourceNames, SOURCES.temporary]),
],
})
return {
type: "FeatureCollection",
features: collection.features
.filter((feature) => {
const temporary = geoman.features.get(SOURCES.temporary, feature.id)
// An unfinished drawing has no home source. A feature being dragged does.
return !temporary || temporary.homeSourceName !== null
})
.map((feature) => ({
...structuredClone(feature),
properties: Object.fromEntries(
Object.entries(feature.properties || {}).filter(
([key]) => !key.startsWith("__gm_") && !key.startsWith("gm_"),
),
),
})),
}
}A completed feature parked for editing has a home source; an unfinished drawing does not. That distinction lets us include the former without exporting the latter.
Review serialization for the shapes your application supports. Circles and text markers may need metadata that a polygon-only cleaning function would discard. Display-only or externally owned data may also need a separate export path.
Preserve precision when switching renderers. Our Leaflet adapter uses toGeoJSON(false) so repeated exports do not round coordinates and gradually change a shape.
Decide what holes, cuts, splits and parts mean for your data
Similar-looking edits can produce different records:
| Tool | Result in this workspace | Feature identity |
|---|---|---|
| Add hole | Insert an interior ring | Same ID |
| Cut | Subtract area; disconnected pieces can form a MultiPolygon |
Same ID if some area survives |
| Split | Divide the original into separate features | New IDs for the children |
| Add part | Add a component, creating a MultiPolygon when needed |
Same ID and shared attributes |
| Move part | Translate one component, including its holes | Same ID; other parts stay put |
| Move hole | Translate an interior ring within its original parent | Same ID and parent part |
A cut covering the entire feature can remove it. A split creates separately identified features. That difference affects ownership, permissions and audit history, so decide it before wiring up persistence.
The MapLibre geometry panel uses interactive add_hole and add_part modes. You can also drive these operations from application code:
const result = await gm.edit.addHole(featureId, holeRing)
if (!result.ok) showGeometryFeedback(result.reason)
await gm.edit.addPart(featureId, partRings, { allowOverlap: false })
await gm.edit.removeRing(featureId, {
kind: "hole",
partIndex: 0,
ringIndex: 1,
})Here, holeRing is a closed coordinate ring; partRings contains the new part's outer ring followed by any holes. Check the result of each operation before showing success. See the programmatic editing API for details.
Move a part without moving the whole feature
Whole-feature Move carries every component and hole together. Move parts is a separate action in the MapLibre inspector. Its tree lets users select a particular part or hole and see exactly what will move.
This drag interaction is application code built on Geoman's API. There is no native "move part" mode behind that button.
We keep the original geometry, record the pointer's starting position, and disable map panning. During the drag, a separate overlay shows the proposed change. Moving a part carries its holes; moving a hole leaves its outer boundary alone.
On release, we validate the candidate and call gm.edit.setGeometry(featureId, candidate) once. An invalid move leaves the stored geometry untouched. Cleanup restores panning even if the pointer is released outside the map or the window loses focus.
That gives us immediate feedback without repeatedly rewriting committed geometry. The city-scale demo uses longitude/latitude translation; a tool for long-distance or high-precision work needs a movement model suited to its coordinate system.
Validate the result, especially at polygon borders
The GeoJSON specification requires closed polygon rings with at least four positions. A square therefore has five positions: its first and last coordinate values are equal. Sharing one mutable JavaScript array between those positions is a separate implementation concern.
Closure alone does not make a polygon valid. Our editing rules also require finite coordinates, enough vertices, usable area, and no invalid intersections. Holes must stay inside their original parent and clear of its boundaries and other holes. New or moved parts must not overlap filled areas under this demo's policy.
For Cut and Split, validate the proposed output before removing or replacing stored features. For ring removal, check the target indices and keep the last required outer shell protected in the UI.
The border-snapping bug
We reproduced a hole that looked snapped to a sloping outer edge but passed a containment check. The map's projected edge and a straight segment in longitude/latitude were close enough to disagree about whether the point touched the border.
The fix checks projected boundary contact as well as containment. The native operation rejects the hole before committing it, and the interface tells the user to keep the opening clear of the outline. If they want to trim material from an edge, Cut is the appropriate tool.
This is a conservative rule for creating interior rings, not a reason to disable snapping. Keep the original geometry, explain the rejection, and let the user adjust the drawing. A production service should validate submitted geometry again with its own spatial tools and business rules.
Connect events to your application and backend
The console labels native Geoman events separately from App events such as session start, cancellation, styling and export. Its Integration tab contains example handlers, not a log of server requests.
We normalize event payloads into IDs and operation details. Passing a live map or feature object straight to JSON can bring in internal state or circular references. Native edit events update the local draft. When the user clicks Done, the app can save the accepted changes.
For a production integration, compare the session's before/after data by ID to find creates, updates and deletes. Submit them together with the project revision and an idempotency key. A Split becomes removal of one original plus creation of its children; a partial Cut usually updates one existing record. Cancel sends neither.
// Integration sketch: this endpoint belongs to your application.
const response = await fetch(
`/api/projects/${projectId}/geometry-transactions`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
"If-Match": projectRevision,
"Idempotency-Key": transactionKey,
},
body: JSON.stringify({ creates, updates, deletes }),
},
)
if (response.status === 409 || response.status === 412) {
throw new Error("The project changed. Reload or resolve the conflict.")
}
if (!response.ok) throw new Error("Save failed. Your edits are still local.")Reuse the transaction key when retrying the same request. The server should check permissions, geometry, attributes and revision, then apply the changes atomically.
Choose one persistence channel for compound operations. Split can emit granular create/remove events and a lineage event containing originalFeatures and features; treating both as independent writes can double-count the edit.
History, renderer changes and larger projects
The full showcase stores snapshots of clean features and appearance. It compares feature IDs and object keys consistently, and batches compound-operation events before adding a history step. For a larger project, a command log or changeset may use less memory than full snapshots.
Switching between MapLibre and Leaflet finishes the active session, reads the data, destroys the old engine, and restores the project in the new one. Basic editing is shared. The advanced holes, parts and custom part-movement UI are MapLibre-first; Leaflet offers a switch for that workflow.
The demo is a small dataset, not a large-scale benchmark. Keep extensive reference data separate from the editable working set, use small overlays for selection and drag previews, and measure history memory. MapLibre's large GeoJSON guide covers rendering choices for bigger datasets.
Test real edits
We test editing through the map, then compare the exported GeoJSON.
Our checks cover repeated polygon movement, editing only the active feature, Split with snapping on and off, invalid holes and overlapping parts, undo/redo, and renderer changes. They also cancel a split and verify that the original ID returns without leaving children behind.
The starter controller has separate tests for actual vertex movement, edit restrictions, rollback and boundary-hole rejection. The article loads its longer code examples from that module, so they stay in sync. We also check mobile controls, server-rendered article content, image decoding and the download.
Common questions
Does Done save to a server?
In the public demo, Done accepts the browser draft. Export GeoJSON to retain it. The save transaction above is a pattern for your own backend.
Does Cut create separate feature records?
A partial Cut keeps the selected feature's ID, even if the result becomes a MultiPolygon. A cut covering the entire feature can remove it. Use Split when you want separate features.
Is the starter the full GIS workspace?
It is a smaller application with selection, scoped editing, snapping, events, export and session rollback. The full showcase adds the richer panels, undo/redo and custom part movement. Neither includes a backend or QGIS's analysis toolbox.
Try it with your own workflow
Open the MapLibre GIS workspace and explore the multipart example in Geometry. The starter download gives you the controller and a small UI to run locally.
For the library APIs, start with MapLibre installation, data layers and programmatic editing. Compare Pro plans or talk to the team about the editor you are building.




