maplibre-gl-geo-editor 0.7.3 → 0.9.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
@@ -11,13 +11,17 @@ A powerful MapLibre GL plugin for creating and editing geometries. Extends the f
11
11
  ## Features
12
12
 
13
13
  ### Draw Tools
14
- - **Polygon** - Draw polygons by clicking points
15
- - **Line** - Draw polylines
14
+ - **Polygon** - Draw polygons by clicking points; **double-click or right-click to finish**
15
+ - **Line** - Draw polylines; **double-click or right-click to finish**
16
16
  - **Rectangle** - Draw rectangles
17
17
  - **Circle** - Draw circles
18
18
  - **Marker** - Place point markers
19
19
  - **Freehand** - Draw shapes by dragging (custom implementation)
20
20
 
21
+ > Polygons and lines can also be completed the Geoman way — by clicking the
22
+ > first/last vertex — but a double-click or right-click ends the shape too, as
23
+ > in most drawing tools.
24
+
21
25
  ### Basic Edit Tools (via Geoman Free)
22
26
  - **Drag** - Move features on the map
23
27
  - **Edit** - Modify feature vertices
@@ -16168,6 +16168,9 @@ class HistoryManager {
16168
16168
  }
16169
16169
  }
16170
16170
  }
16171
+ function resolveImportedCount(result, fallback) {
16172
+ return result?.stats?.success ?? result?.success ?? fallback;
16173
+ }
16171
16174
  class CreateFeatureCommand {
16172
16175
  description;
16173
16176
  type = "create";
@@ -16660,18 +16663,25 @@ function radiansToDegrees(radians2) {
16660
16663
  return radians2 * 180 / Math.PI;
16661
16664
  }
16662
16665
  function roundCoordinates(coordinates, precision2 = 6) {
16663
- return [
16664
- Number(coordinates[0].toFixed(precision2)),
16665
- Number(coordinates[1].toFixed(precision2))
16666
- ];
16666
+ return coordinates.map(
16667
+ (value) => Number(value.toFixed(precision2))
16668
+ );
16667
16669
  }
16668
16670
  function positionsEqual(pos1, pos2, tolerance = 1e-9) {
16669
- return Math.abs(pos1[0] - pos2[0]) < tolerance && Math.abs(pos1[1] - pos2[1]) < tolerance;
16671
+ if (pos1.length !== pos2.length) {
16672
+ return false;
16673
+ }
16674
+ return pos1.every(
16675
+ (value, index) => Math.abs(value - pos2[index]) < tolerance
16676
+ );
16670
16677
  }
16671
16678
  function getVertexCount(feature2) {
16672
16679
  return coordAll(feature2).length;
16673
16680
  }
16674
16681
  function cloneFeature(feature2) {
16682
+ if (typeof structuredClone === "function") {
16683
+ return structuredClone(feature2);
16684
+ }
16675
16685
  return JSON.parse(JSON.stringify(feature2));
16676
16686
  }
16677
16687
  class CopyFeature {
@@ -18361,6 +18371,9 @@ class GeoEditor {
18361
18371
  // Event listeners
18362
18372
  boundKeyHandler = null;
18363
18373
  boundClickHandler = null;
18374
+ // Finish an in-progress polygon/line draw on double-click or right-click.
18375
+ boundDrawFinishDblClick = null;
18376
+ boundDrawFinishContextMenu = null;
18364
18377
  boundScaleMouseDown = null;
18365
18378
  boundScaleMouseMove = null;
18366
18379
  boundScaleMouseUp = null;
@@ -18460,6 +18473,7 @@ class GeoEditor {
18460
18473
  this.setupSelectionHandler();
18461
18474
  this.setupScaleHandler();
18462
18475
  this.setupMultiDragHandler();
18476
+ this.setupDrawFinishHandlers();
18463
18477
  this.setupVertexMarkerStyleListener();
18464
18478
  this.setupGeomanEvents();
18465
18479
  if (this.options.enableAttributeEditing) {
@@ -18478,6 +18492,7 @@ class GeoEditor {
18478
18492
  this.removeSelectionHandler();
18479
18493
  this.removeScaleHandler();
18480
18494
  this.removeMultiDragHandler();
18495
+ this.removeDrawFinishHandlers();
18481
18496
  this.removeVertexMarkerStyleListener();
18482
18497
  this.disableAllModes();
18483
18498
  this.hideFeaturePropertiesPopup();
@@ -19230,6 +19245,118 @@ class GeoEditor {
19230
19245
  this.updateToolbarState();
19231
19246
  this.applySnappingState();
19232
19247
  }
19248
+ // ============================================================================
19249
+ // Finish polygon/line draw on double-click or right-click
19250
+ // ============================================================================
19251
+ /**
19252
+ * Attach map listeners that finish an in-progress polygon or line on a
19253
+ * double-click or right-click.
19254
+ *
19255
+ * Geoman free only completes these shapes when the user clicks the first or
19256
+ * last vertex, which is unintuitive: every other drawing tool ends a polygon
19257
+ * with a double-click (or right-click). These handlers add that gesture while
19258
+ * leaving the click-the-first-vertex behavior intact.
19259
+ */
19260
+ setupDrawFinishHandlers() {
19261
+ if (!this.map) return;
19262
+ const handler = (e) => {
19263
+ if (this.state.activeDrawMode !== "polygon" && this.state.activeDrawMode !== "line") {
19264
+ return;
19265
+ }
19266
+ if (this.finishActiveLineOrPolygonDraw()) {
19267
+ e.preventDefault();
19268
+ }
19269
+ };
19270
+ this.boundDrawFinishDblClick = handler;
19271
+ this.boundDrawFinishContextMenu = handler;
19272
+ this.map.on("dblclick", this.boundDrawFinishDblClick);
19273
+ this.map.on("contextmenu", this.boundDrawFinishContextMenu);
19274
+ }
19275
+ /**
19276
+ * Remove the double-click / right-click draw-finish listeners.
19277
+ */
19278
+ removeDrawFinishHandlers() {
19279
+ if (!this.map) return;
19280
+ if (this.boundDrawFinishDblClick) {
19281
+ this.map.off("dblclick", this.boundDrawFinishDblClick);
19282
+ this.boundDrawFinishDblClick = null;
19283
+ }
19284
+ if (this.boundDrawFinishContextMenu) {
19285
+ this.map.off("contextmenu", this.boundDrawFinishContextMenu);
19286
+ this.boundDrawFinishContextMenu = null;
19287
+ }
19288
+ }
19289
+ /**
19290
+ * Finish the polygon or line currently being drawn, as if the user had
19291
+ * clicked the closing vertex.
19292
+ *
19293
+ * This drives Geoman's own draw instance so the resulting geometry, cleanup,
19294
+ * and `gm:create` event match a normally-finished shape. Geoman's draw
19295
+ * internals are not part of the public API, so every access is feature-detected
19296
+ * and the method bails (leaving drawing untouched) if the shape cannot be
19297
+ * finished — e.g. too few vertices, or an incompatible Geoman build.
19298
+ *
19299
+ * @returns true when a shape was finished, false otherwise.
19300
+ */
19301
+ finishActiveLineOrPolygonDraw() {
19302
+ const mode = this.state.activeDrawMode;
19303
+ if (mode !== "polygon" && mode !== "line") return false;
19304
+ if (!this.geoman) return false;
19305
+ try {
19306
+ const instances = this.geoman.actionInstances;
19307
+ const instance = instances?.[`draw__${mode}`];
19308
+ const drawer = instance?.lineDrawer;
19309
+ if (!drawer || typeof drawer.getMarkerClickEventData !== "function") {
19310
+ return false;
19311
+ }
19312
+ const coords = Array.isArray(drawer.shapeLngLats) ? drawer.shapeLngLats : [];
19313
+ const count = coords.length;
19314
+ if (count === 0) return false;
19315
+ const hasTrailingDuplicate = count >= 2 && this.lngLatsEqual(coords[count - 1], coords[count - 2]);
19316
+ if (mode === "line") {
19317
+ const endIndex = hasTrailingDuplicate ? count - 2 : count - 1;
19318
+ if (endIndex < 1) return false;
19319
+ const eventData2 = drawer.getMarkerClickEventData(endIndex);
19320
+ if (typeof instance.lineFinished !== "function") return false;
19321
+ instance.lineFinished(eventData2);
19322
+ return true;
19323
+ }
19324
+ const eventData = drawer.getMarkerClickEventData(count - 1);
19325
+ const ring = eventData?.geoJson?.geometry?.coordinates;
19326
+ if (hasTrailingDuplicate && Array.isArray(ring) && ring.length >= 2) {
19327
+ ring.pop();
19328
+ }
19329
+ const ringLength = Array.isArray(ring) ? ring.length : count;
19330
+ if (ringLength < 3) return false;
19331
+ if (typeof instance.polygonFinished !== "function") return false;
19332
+ instance.polygonFinished(eventData);
19333
+ return true;
19334
+ } catch {
19335
+ return false;
19336
+ }
19337
+ }
19338
+ /**
19339
+ * Compare two Geoman vertices for equality. Geoman stores vertices as either
19340
+ * `[lng, lat]` tuples or MapLibre `LngLat` objects, so normalize both forms.
19341
+ */
19342
+ lngLatsEqual(a, b) {
19343
+ const toPair = (p) => {
19344
+ if (Array.isArray(p) && typeof p[0] === "number" && typeof p[1] === "number") {
19345
+ return [p[0], p[1]];
19346
+ }
19347
+ if (p && typeof p === "object") {
19348
+ const o = p;
19349
+ if (typeof o.lng === "number" && typeof o.lat === "number") {
19350
+ return [o.lng, o.lat];
19351
+ }
19352
+ }
19353
+ return null;
19354
+ };
19355
+ const pa = toPair(a);
19356
+ const pb = toPair(b);
19357
+ if (!pa || !pb) return false;
19358
+ return Math.abs(pa[0] - pb[0]) < 1e-9 && Math.abs(pa[1] - pb[1]) < 1e-9;
19359
+ }
19233
19360
  /**
19234
19361
  * Enable an advanced edit mode
19235
19362
  */
@@ -20641,13 +20768,13 @@ class GeoEditor {
20641
20768
  const file = input.files?.[0];
20642
20769
  if (!file) return;
20643
20770
  const reader = new FileReader();
20644
- reader.onload = (e) => {
20771
+ reader.onload = async (e) => {
20645
20772
  try {
20646
20773
  const content = e.target?.result;
20647
20774
  const geoJson = JSON.parse(content);
20648
- this.loadGeoJson(geoJson, file.name);
20775
+ await this.loadGeoJson(geoJson, file.name);
20649
20776
  } catch (error) {
20650
- console.error("GeoEditor: Failed to parse GeoJSON file:", error);
20777
+ console.error("GeoEditor: Failed to load GeoJSON file:", error);
20651
20778
  const errorInfo = {
20652
20779
  filename: file.name,
20653
20780
  message: error instanceof Error ? error.message : String(error),
@@ -20660,17 +20787,31 @@ class GeoEditor {
20660
20787
  input.value = "";
20661
20788
  }
20662
20789
  /**
20663
- * Load GeoJSON data into the editor
20790
+ * Load GeoJSON data into the editor.
20791
+ *
20792
+ * Resolves once geoman has finished importing the features. This is `async`
20793
+ * because geoman's `deleteAll` and `importGeoJson` are asynchronous in current
20794
+ * geoman releases: awaiting them prevents a reload from racing the previous
20795
+ * clear, and lets the returned `count` reflect the actual import result rather
20796
+ * than a not-yet-resolved promise.
20797
+ *
20664
20798
  * @param geoJson - FeatureCollection or Feature to load
20665
20799
  * @param filename - Optional filename for logging
20666
20800
  * @returns Result of the load operation
20667
20801
  */
20668
- loadGeoJson(geoJson, filename = "loaded.geojson") {
20802
+ async loadGeoJson(geoJson, filename = "loaded.geojson") {
20669
20803
  if (!this.geoman) {
20670
20804
  throw new Error("Geoman not initialized");
20671
20805
  }
20806
+ const geoman = this.geoman;
20807
+ if (geoman.loaded === false && typeof geoman.waitForGeomanLoaded === "function") {
20808
+ try {
20809
+ await geoman.waitForGeomanLoaded();
20810
+ } catch {
20811
+ }
20812
+ }
20672
20813
  try {
20673
- this.geoman.features.deleteAll();
20814
+ await this.geoman.features.deleteAll();
20674
20815
  } catch {
20675
20816
  this.geoman.features.forEach((fd) => {
20676
20817
  try {
@@ -20691,10 +20832,12 @@ class GeoEditor {
20691
20832
  } else {
20692
20833
  throw new Error("Invalid GeoJSON: expected Feature or FeatureCollection");
20693
20834
  }
20694
- const importResult = this.geoman.features.importGeoJson(featureCollection2);
20835
+ const importResult = await this.geoman.features.importGeoJson(
20836
+ featureCollection2
20837
+ );
20695
20838
  const result = {
20696
20839
  features: featureCollection2.features,
20697
- count: importResult.success,
20840
+ count: resolveImportedCount(importResult, featureCollection2.features.length),
20698
20841
  filename
20699
20842
  };
20700
20843
  if (this.options.fitBoundsOnLoad && featureCollection2.features.length > 0) {
@@ -21574,4 +21717,4 @@ export {
21574
21717
  createPolygon as y,
21575
21718
  createLine as z
21576
21719
  };
21577
- //# sourceMappingURL=geo-editor-CkbsCEqw.js.map
21720
+ //# sourceMappingURL=geo-editor-C_QnBCMc.js.map