maplibre-gl-geo-editor 0.10.4 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -60,9 +60,154 @@ A powerful MapLibre GL plugin for creating and editing geometries. Extends the f
60
60
  ## Installation
61
61
 
62
62
  ```bash
63
- npm install maplibre-gl-geo-editor @geoman-io/maplibre-geoman-free maplibre-gl
63
+ npm install maplibre-gl-geo-editor @geoman-io/maplibre-geoman-free@^0.9.1 maplibre-gl@^6
64
64
  ```
65
65
 
66
+ Requires Geoman Free 0.9.1 (0.9.x) and MapLibre GL JS 6.x. Both dependencies
67
+ use ESM; MapLibre 6 requires named or namespace imports rather than a default import.
68
+
69
+ With Vite, configure the worker before creating any maps:
70
+
71
+ ```typescript
72
+ import { setWorkerUrl } from 'maplibre-gl';
73
+ import workerUrl from 'maplibre-gl/dist/maplibre-gl-worker.mjs?worker&url';
74
+ setWorkerUrl(workerUrl);
75
+ ```
76
+
77
+ The `?worker&url` query bundles the worker's dependencies for production too.
78
+ Other bundlers require their own worker setup; see the
79
+ [MapLibre installation guide](https://maplibre.org/maplibre-gl-js/docs/#installation).
80
+
81
+
82
+ ## Snap target events
83
+
84
+ Enable local snap observation to identify the feature and vertex or segment
85
+ selected by Geoman. No Geoman fork or upstream patch is required.
86
+
87
+ ```typescript
88
+ const editor = new GeoEditor({
89
+ snapEventsEnabled: true,
90
+ onSnap: ({ coordinate, target }) => {
91
+ if (target.kind === 'custom') return; // No feature identity for custom coordinates
92
+ console.log(target.featureId, target.feature.properties, coordinate);
93
+ if (target.kind === 'vertex') {
94
+ console.log(target.coordinatePath); // e.g. ['geometry', 'coordinates', 2]
95
+ } else {
96
+ console.log(target.segmentPaths); // Paths to both segment endpoints
97
+ }
98
+ },
99
+ onUnsnap: () => console.log('Snap target cleared'),
100
+ });
101
+ ```
102
+
103
+ The same payloads are emitted as `CustomEvent.detail` on `map.getContainer()`
104
+ under `gm:snap` and `gm:unsnap`, following this editor's existing event convention.
105
+ These are not MapLibre `map.on()` events. `onSnap` fires for each resolved snap
106
+ calculation; `onUnsnap` fires when the target changes or is cleared.
107
+ `editor.getSnapTarget()` returns a copy of the latest preview or `null`.
108
+ `editor.isSnapTrackingAvailable()` reports whether an active compatible snapping
109
+ helper is being observed; it is false while the helper is disabled or unavailable.
110
+
111
+ Targets contain a snapshot of the target GeoJSON and its properties. `featureId`
112
+ is Geoman's ID, not automatically an OSM ID; use your application's identity
113
+ mapping. Paths address the snapshot Feature, including polygon ring and multipart
114
+ indices. Coincident features follow Geoman's actual selection order. Custom snaps
115
+ have no feature metadata, and temporary feature targets are marked `temporary`.
116
+
117
+ **These are preview events, not vertex-commit events.** Applications must associate
118
+ previews with their draw/edit transactions and verify the committed vertex before
119
+ changing node references. This feature does not merge nodes, preserve an OSM graph,
120
+ or generate changesets. Keep NWR IDs, versions, and relations in application state.
121
+
122
+ The observer wraps methods on the active helper instance and restores them when
123
+ Geoman is replaced or the editor is removed. Its internal integration and segment
124
+ selection assumptions are tested against Geoman Free 0.9.1. Run the snap tests
125
+ when upgrading Geoman; unsupported helper shapes leave tracking unavailable.
126
+
127
+ ### Getting the identity of a snapped node
128
+
129
+ Use the selected feature **and its vertex path** to look up the node identity.
130
+ `target.featureId` identifies the Geoman feature (for example, a way), while
131
+ `target.coordinatePath` identifies the vertex within that feature. Equal
132
+ coordinates alone do not establish that two vertices are the same OSM node.
133
+
134
+ Store the original node IDs and versions alongside your geometry when loading
135
+ data. For example, a three-vertex LineString can carry these application-defined
136
+ properties, ordered exactly like its `geometry.coordinates`:
137
+
138
+ ```typescript
139
+ const properties = {
140
+ osm_id: 'way/201',
141
+ osm_version: 7,
142
+ node_ids: ['node/101', 'node/102', 'node/103'],
143
+ node_versions: [2, 5, 1],
144
+ };
145
+ ```
146
+
147
+ Then resolve vertex snaps in the editor callback:
148
+
149
+ ```typescript
150
+ import { GeoEditor } from 'maplibre-gl-geo-editor';
151
+
152
+ const editor = new GeoEditor({
153
+ snapEventsEnabled: true,
154
+ onSnap: ({ target }) => {
155
+ if (target.kind !== 'vertex') return;
156
+ const feature = target.feature;
157
+ if (feature.geometry.type !== 'LineString') return;
158
+
159
+ // LineString path: ['geometry', 'coordinates', vertexIndex]
160
+ const vertexIndex = target.coordinatePath[2];
161
+ const { node_ids, node_versions } = feature.properties ?? {};
162
+ if (typeof vertexIndex !== 'number' || !Array.isArray(node_ids)) return;
163
+ if (node_ids.length !== feature.geometry.coordinates.length) return;
164
+
165
+ console.log({
166
+ featureId: target.featureId,
167
+ nodeId: node_ids[vertexIndex],
168
+ nodeVersion: Array.isArray(node_versions) && node_versions.length === node_ids.length
169
+ ? node_versions[vertexIndex]
170
+ : undefined,
171
+ });
172
+ },
173
+ });
174
+
175
+ // Connect to your existing Geoman instance and map.
176
+ editor.setGeoman(geoman);
177
+ map.addControl(editor, 'top-left');
178
+ ```
179
+
180
+ The `node_ids` and `node_versions` fields above are your application's metadata;
181
+ Geoman does not fetch or populate them. A way's version is separate from each
182
+ referenced node's version. You can instead keep this information in an external
183
+ store keyed by the editor feature ID and vertex path.
184
+
185
+ For other geometries, include every part and ring index when resolving a path:
186
+
187
+ | Target geometry | Vertex path | Suggested node-ID lookup |
188
+ | --- | --- | --- |
189
+ | LineString | `['geometry', 'coordinates', vertex]` | `node_ids[vertex]` |
190
+ | MultiLineString | `['geometry', 'coordinates', part, vertex]` | `node_ids[part][vertex]` |
191
+ | Polygon | `['geometry', 'coordinates', ring, vertex]` | `node_ids[ring][vertex]` |
192
+ | MultiPolygon | `['geometry', 'coordinates', polygon, ring, vertex]` | `node_ids[polygon][ring][vertex]` |
193
+
194
+ For polygons, ring `0` is the exterior and later rings are holes. Mirror that
195
+ structure in your metadata; the closing coordinate must reference the same node
196
+ ID as the first coordinate. For a segment snap, resolve both paths in
197
+ `target.segmentPaths` to identify its endpoint nodes. A snap to the segment's
198
+ interior does not identify an existing node at the snapped position.
199
+
200
+ Keep these mappings synchronized with edits: moving a vertex retains its ID,
201
+ inserting a vertex adds a new local ID, and deleting a vertex removes its
202
+ reference. Do not simply renumber existing nodes after an insertion. Connecting
203
+ or merging nodes requires an explicit application-level topology operation when
204
+ the edit is committed, rather than updating references on every snap preview.
205
+
206
+ Try the [Snap Target Inspector](examples/snapping/index.html) on the examples
207
+ page. It displays node IDs, way versions, segment
208
+ endpoints, and the event payload. Its LineString demo preserves existing IDs
209
+ during vertex edits and assigns inserted vertices IDs such as `local/node-1`.
210
+
66
211
  ## Usage
67
212
 
68
213
  ### Basic Usage (Vanilla JS/TS)
@@ -72,7 +217,7 @@ import 'maplibre-gl/dist/maplibre-gl.css';
72
217
  import '@geoman-io/maplibre-geoman-free/dist/maplibre-geoman.css';
73
218
  import 'maplibre-gl-geo-editor/style.css';
74
219
 
75
- import maplibregl from 'maplibre-gl';
220
+ import * as maplibregl from 'maplibre-gl';
76
221
  import { Geoman } from '@geoman-io/maplibre-geoman-free';
77
222
  import { GeoEditor } from 'maplibre-gl-geo-editor';
78
223
 
@@ -208,7 +353,7 @@ const schema = geoEditor.getAttributeSchema();
208
353
 
209
354
  ```tsx
210
355
  import { useEffect, useRef, useState } from 'react';
211
- import maplibregl from 'maplibre-gl';
356
+ import * as maplibregl from 'maplibre-gl';
212
357
  import { Geoman } from '@geoman-io/maplibre-geoman-free';
213
358
  import { GeoEditorReact } from 'maplibre-gl-geo-editor/react';
214
359
 
@@ -16057,6 +16057,157 @@ function unkinkPolygon(geojson) {
16057
16057
  });
16058
16058
  return featureCollection(features);
16059
16059
  }
16060
+ function visitGeometry(geometry, vertex, segment, path = ["geometry"]) {
16061
+ if (geometry.type === "GeometryCollection") {
16062
+ geometry.geometries.forEach(
16063
+ (part, index) => visitGeometry(part, vertex, segment, [...path, "geometries", index])
16064
+ );
16065
+ return;
16066
+ }
16067
+ const isPosition = (value) => Array.isArray(value) && typeof value[0] === "number";
16068
+ function walk(value, currentPath) {
16069
+ if (isPosition(value)) {
16070
+ vertex({ coordinate: [value[0], value[1]], path: currentPath });
16071
+ } else if (Array.isArray(value)) {
16072
+ value.forEach((item, index) => {
16073
+ walk(item, [...currentPath, index]);
16074
+ const next = value[index + 1];
16075
+ if (geometry.type !== "MultiPoint" && isPosition(item) && isPosition(next)) {
16076
+ segment(
16077
+ { coordinate: [item[0], item[1]], path: [...currentPath, index] },
16078
+ {
16079
+ coordinate: [next[0], next[1]],
16080
+ path: [...currentPath, index + 1]
16081
+ }
16082
+ );
16083
+ }
16084
+ });
16085
+ }
16086
+ }
16087
+ walk(geometry.coordinates, [...path, "coordinates"]);
16088
+ }
16089
+ function observeSnapping(value, notify) {
16090
+ const helper = value;
16091
+ if (!helper || typeof helper.getSnappedLngLat !== "function" || typeof helper.getPointsSnapping !== "function" || typeof helper.getCustomLngLatsSnapping !== "function" || !helper.shapeSnappingHandlers || typeof helper.gm?.mapAdapter?.project !== "function")
16092
+ return null;
16093
+ let captures = null;
16094
+ const restorers = [];
16095
+ function wrap(object, key, replacement) {
16096
+ const original2 = object[key];
16097
+ const own = Object.prototype.hasOwnProperty.call(object, key);
16098
+ object[key] = replacement;
16099
+ restorers.push(() => {
16100
+ if (object[key] !== replacement) return;
16101
+ if (own) object[key] = original2;
16102
+ else delete object[key];
16103
+ });
16104
+ }
16105
+ function capture(handler, kind) {
16106
+ return function(feature2, lngLat, point2) {
16107
+ const result = handler.call(helper, feature2, lngLat, point2);
16108
+ captures?.push({ result, feature: feature2, kind });
16109
+ return result;
16110
+ };
16111
+ }
16112
+ wrap(
16113
+ helper,
16114
+ "getPointsSnapping",
16115
+ capture(helper.getPointsSnapping, "vertex")
16116
+ );
16117
+ for (const [shape, handler] of Object.entries(helper.shapeSnappingHandlers)) {
16118
+ if (handler)
16119
+ wrap(helper.shapeSnappingHandlers, shape, capture(handler, "segment"));
16120
+ }
16121
+ const custom = helper.getCustomLngLatsSnapping;
16122
+ wrap(helper, "getCustomLngLatsSnapping", function(point2) {
16123
+ const lngLat = custom.call(helper, point2);
16124
+ if (lngLat)
16125
+ captures?.push({ result: { lngLat, distance: 0 }, kind: "custom" });
16126
+ return lngLat;
16127
+ });
16128
+ const original = helper.getSnappedLngLat;
16129
+ wrap(helper, "getSnappedLngLat", function(lngLat, point2) {
16130
+ const previous = captures;
16131
+ const observed = [];
16132
+ captures = observed;
16133
+ let coordinate;
16134
+ try {
16135
+ coordinate = original.call(helper, lngLat, point2);
16136
+ } finally {
16137
+ captures = previous;
16138
+ }
16139
+ const winner = observed.find(
16140
+ ({ result, kind }) => result.lngLat === coordinate && (kind === "custom" || result.distance < helper.tolerance)
16141
+ );
16142
+ const target = winner ? describeTarget(helper, winner, lngLat) : null;
16143
+ notify(
16144
+ target ? {
16145
+ coordinate: [...coordinate],
16146
+ pointerCoordinate: [...lngLat],
16147
+ target
16148
+ } : null
16149
+ );
16150
+ return coordinate;
16151
+ });
16152
+ return () => {
16153
+ restorers.reverse().forEach((restore) => restore());
16154
+ };
16155
+ }
16156
+ function describeTarget(helper, winner, pointer) {
16157
+ if (!winner.feature) return { kind: "custom" };
16158
+ const feature2 = winner.feature.getGeoJson?.() ?? winner.feature.geoJson;
16159
+ if (!feature2) return null;
16160
+ const snapshot = structuredClone(feature2);
16161
+ const base = {
16162
+ featureId: winner.feature.id,
16163
+ feature: snapshot,
16164
+ temporary: !!winner.feature.temporary
16165
+ };
16166
+ if (winner.kind === "vertex") {
16167
+ let coordinatePath;
16168
+ visitGeometry(
16169
+ feature2.geometry,
16170
+ (position) => {
16171
+ if (!coordinatePath && position.coordinate[0] === winner.result.lngLat[0] && position.coordinate[1] === winner.result.lngLat[1])
16172
+ coordinatePath = [...position.path];
16173
+ },
16174
+ () => {
16175
+ }
16176
+ );
16177
+ return coordinatePath ? { ...base, kind: "vertex", coordinatePath } : null;
16178
+ }
16179
+ const screen = helper.gm.mapAdapter.project(pointer);
16180
+ let distance2 = Infinity;
16181
+ let segmentPaths;
16182
+ visitGeometry(
16183
+ feature2.geometry,
16184
+ () => {
16185
+ },
16186
+ (start, end) => {
16187
+ const a = helper.gm.mapAdapter.project(start.coordinate);
16188
+ const b = helper.gm.mapAdapter.project(end.coordinate);
16189
+ const dx = b[0] - a[0];
16190
+ const dy = b[1] - a[1];
16191
+ const lengthSquared = dx * dx + dy * dy;
16192
+ const fraction = lengthSquared === 0 ? 0 : Math.max(
16193
+ 0,
16194
+ Math.min(
16195
+ 1,
16196
+ ((screen[0] - a[0]) * dx + (screen[1] - a[1]) * dy) / lengthSquared
16197
+ )
16198
+ );
16199
+ const nearest = [a[0] + fraction * dx, a[1] + fraction * dy];
16200
+ const candidateDistance = Math.sqrt(
16201
+ (screen[0] - nearest[0]) ** 2 + (screen[1] - nearest[1]) ** 2
16202
+ );
16203
+ if (candidateDistance < distance2) {
16204
+ distance2 = candidateDistance;
16205
+ segmentPaths = [[...start.path], [...end.path]];
16206
+ }
16207
+ }
16208
+ );
16209
+ return segmentPaths ? { ...base, kind: "segment", segmentPaths } : null;
16210
+ }
16060
16211
  class HistoryManager {
16061
16212
  undoStack = [];
16062
16213
  redoStack = [];
@@ -16598,6 +16749,11 @@ const DEFAULT_OPTIONS = {
16598
16749
  showLabels: false,
16599
16750
  simplifyTolerance: 1e-3,
16600
16751
  snappingEnabled: true,
16752
+ snapEventsEnabled: false,
16753
+ onSnap: () => {
16754
+ },
16755
+ onUnsnap: () => {
16756
+ },
16601
16757
  topologyEnabled: false,
16602
16758
  measurementsEnabled: false,
16603
16759
  hideGeomanControl: true,
@@ -18497,6 +18653,10 @@ function generateTempId() {
18497
18653
  class GeoEditor {
18498
18654
  map;
18499
18655
  geoman = null;
18656
+ observedSnappingHelper = null;
18657
+ detachSnapObserver = null;
18658
+ currentSnap = null;
18659
+ snapObserverRemoved = false;
18500
18660
  container;
18501
18661
  options;
18502
18662
  state;
@@ -18617,6 +18777,7 @@ class GeoEditor {
18617
18777
  * Called when the control is added to the map
18618
18778
  */
18619
18779
  onAdd(map) {
18780
+ this.snapObserverRemoved = false;
18620
18781
  this.map = map;
18621
18782
  this.scaleFeature.init(map);
18622
18783
  this.lassoFeature.init(map);
@@ -18646,6 +18807,8 @@ class GeoEditor {
18646
18807
  * Called when the control is removed from the map
18647
18808
  */
18648
18809
  onRemove() {
18810
+ this.snapObserverRemoved = true;
18811
+ this.clearSnapObserver();
18649
18812
  this.removeKeyboardShortcuts();
18650
18813
  this.removeSelectionHandler();
18651
18814
  this.removeScaleHandler();
@@ -18676,6 +18839,8 @@ class GeoEditor {
18676
18839
  */
18677
18840
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
18678
18841
  setGeoman(geoman) {
18842
+ if (this.geoman === geoman) return;
18843
+ this.clearSnapObserver();
18679
18844
  this.geoman = geoman;
18680
18845
  this.setupGeomanEvents();
18681
18846
  this.applySnappingState();
@@ -18694,7 +18859,7 @@ class GeoEditor {
18694
18859
  const geoman = new Geoman(this.map);
18695
18860
  geoman.addControls = async () => {
18696
18861
  };
18697
- geoman.removeControls = () => {
18862
+ geoman.removeControls = async () => {
18698
18863
  };
18699
18864
  this.setGeoman(geoman);
18700
18865
  }
@@ -21421,6 +21586,11 @@ class GeoEditor {
21421
21586
  );
21422
21587
  }
21423
21588
  applySnappingState() {
21589
+ if (!this.snappingEnabled) this.clearSnapObserver();
21590
+ this.applyGeomanSnappingMode();
21591
+ if (this.snappingEnabled) this.refreshSnapObserver();
21592
+ }
21593
+ applyGeomanSnappingMode() {
21424
21594
  if (!this.geoman) {
21425
21595
  return;
21426
21596
  }
@@ -21713,12 +21883,17 @@ class GeoEditor {
21713
21883
  }
21714
21884
  setupGeomanEvents() {
21715
21885
  if (!this.geoman) return;
21886
+ this.refreshSnapObserver();
21887
+ const observedGeoman = this.geoman;
21716
21888
  this.geoman.setGlobalEventsListener((event) => {
21889
+ if (this.snapObserverRemoved || this.geoman !== observedGeoman) return;
21890
+ this.refreshSnapObserver();
21717
21891
  const eventName = event.name ?? event.type ?? "";
21718
21892
  const eventFeature = this.extractFeatureFromEvent(
21719
21893
  event.feature
21720
21894
  );
21721
21895
  const eventAction = event.action ?? "";
21896
+ if (eventAction === "mode_end") this.updateSnap(null);
21722
21897
  if ((eventName === "gm:create" || event.type === "gm:create") && eventFeature) {
21723
21898
  if (this.state.activeDrawMode === "massing" && (eventFeature.geometry.type === "Polygon" || eventFeature.geometry.type === "MultiPolygon")) {
21724
21899
  eventFeature.properties = {
@@ -21790,6 +21965,56 @@ class GeoEditor {
21790
21965
  const event = new CustomEvent(type, { detail });
21791
21966
  this.map.getContainer().dispatchEvent(event);
21792
21967
  }
21968
+ /** Latest snap preview, copied for the caller. Not a committed topology edit. */
21969
+ getSnapTarget() {
21970
+ return this.currentSnap ? structuredClone(this.currentSnap) : null;
21971
+ }
21972
+ /** Whether the currently active Geoman snapping helper can be observed. */
21973
+ isSnapTrackingAvailable() {
21974
+ return this.detachSnapObserver !== null;
21975
+ }
21976
+ updateSnap(event) {
21977
+ const previous = this.currentSnap;
21978
+ const key = (snap) => {
21979
+ const target = snap.target;
21980
+ return target.kind === "custom" ? JSON.stringify(["custom", snap.coordinate]) : JSON.stringify([
21981
+ target.kind,
21982
+ target.featureId,
21983
+ target.temporary,
21984
+ target.kind === "vertex" ? target.coordinatePath : target.segmentPaths
21985
+ ]);
21986
+ };
21987
+ this.currentSnap = event;
21988
+ if (previous && (!event || key(previous) !== key(event))) {
21989
+ const detail = structuredClone(previous);
21990
+ this.options.onUnsnap?.(detail);
21991
+ if (this.map) this.emitEvent("gm:unsnap", detail);
21992
+ }
21993
+ if (event) {
21994
+ const detail = structuredClone(event);
21995
+ this.options.onSnap?.(detail);
21996
+ if (this.map) this.emitEvent("gm:snap", detail);
21997
+ }
21998
+ }
21999
+ clearSnapObserver() {
22000
+ this.detachSnapObserver?.();
22001
+ this.detachSnapObserver = null;
22002
+ this.observedSnappingHelper = null;
22003
+ this.updateSnap(null);
22004
+ }
22005
+ refreshSnapObserver() {
22006
+ if (this.snapObserverRemoved || !this.map || !this.options.snapEventsEnabled || !this.snappingEnabled) {
22007
+ return;
22008
+ }
22009
+ const helper = this.geoman?.actionInstances?.helper__snapping ?? null;
22010
+ if (helper === this.observedSnappingHelper) return;
22011
+ this.clearSnapObserver();
22012
+ this.observedSnappingHelper = helper;
22013
+ this.detachSnapObserver = observeSnapping(
22014
+ helper,
22015
+ (event) => this.updateSnap(event)
22016
+ );
22017
+ }
21793
22018
  // ============================================================================
21794
22019
  // History Management (Undo/Redo)
21795
22020
  // ============================================================================
@@ -22325,4 +22550,4 @@ export {
22325
22550
  createPolygon as y,
22326
22551
  createLine as z
22327
22552
  };
22328
- //# sourceMappingURL=geo-editor-RiqEfzJp.js.map
22553
+ //# sourceMappingURL=geo-editor-ClMk0uQZ.js.map