@apexara/map 1.1.1 → 1.3.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.
@@ -1,12 +1,13 @@
1
1
  import { isPlatformBrowser } from '@angular/common';
2
2
  import * as i0 from '@angular/core';
3
- import { signal, inject, PLATFORM_ID, Injectable, input, output, DestroyRef, viewChild, effect, ViewEncapsulation, ChangeDetectionStrategy, Component } from '@angular/core';
3
+ import { signal, inject, PLATFORM_ID, Injectable, input, output, DestroyRef, viewChild, effect, ViewEncapsulation, ChangeDetectionStrategy, Component, ElementRef, Directive } from '@angular/core';
4
4
  import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
5
5
  import { Subject } from 'rxjs';
6
6
  import MapboxDraw from '@mapbox/mapbox-gl-draw';
7
7
  import mapboxgl from 'mapbox-gl';
8
8
  import { MAP_CONFIG, MapStyles } from '@apexara/map/config';
9
9
  export { MAP_CONFIG, MapStyles, provideMap } from '@apexara/map/config';
10
+ import { MapGeolocationUtil, MapGeometryUtil } from '@apexara/map/geo';
10
11
 
11
12
  /**
12
13
  * Mapbox Service — wrapper around a `mapboxgl.Map` instance.
@@ -58,6 +59,8 @@ class MapboxService {
58
59
  this.activeContainer = this._activeContainer;
59
60
  // Whether this browser can run mapbox; null until asked. Kept, since mapbox's check builds a worker and a canvas.
60
61
  this.supported = null;
62
+ // What `fitBounds` has always done: 40 px all round, a one-second slide.
63
+ this.fitDefaults = { padding: 40, duration: 1000 };
61
64
  }
62
65
  /** Back-compat wrapper around `activate`. SSR-safe. */
63
66
  async init(options) {
@@ -275,9 +278,9 @@ class MapboxService {
275
278
  */
276
279
  async getClusterProperties(sourceId, clusterId, limit = 10000, offset = 0) {
277
280
  return new Promise((resolve, reject) => {
278
- const src = this.map.getSource(sourceId);
279
- if (!src || typeof src.getClusterLeaves !== 'function') {
280
- reject(new Error(`Source '${sourceId}' is not a clustered GeoJSON source or is missing.`));
281
+ const src = this.clusterSourceOf(sourceId);
282
+ if (!src) {
283
+ reject(this.notClusteredError(sourceId));
281
284
  return;
282
285
  }
283
286
  src.getClusterLeaves(clusterId, limit, offset, (err, features) => {
@@ -291,29 +294,99 @@ class MapboxService {
291
294
  });
292
295
  }
293
296
  /**
294
- * Query features rendered at a screen point, optionally restricted to specific layers.
295
- * Returns `[]` when the map has not been initialised yet.
297
+ * The zoom at which a cluster splits into its children, e.g. to `easeTo` it. Rejects as `getClusterProperties` does,
298
+ * and when mapbox answers with no zoom.
296
299
  */
297
- getRenderedFeatures(point, params) {
298
- return this.map ? this.map.queryRenderedFeatures(point, params) : [];
300
+ getClusterExpansionZoom(sourceId, clusterId) {
301
+ return new Promise((resolve, reject) => {
302
+ const source = this.clusterSourceOf(sourceId);
303
+ if (!source) {
304
+ reject(this.notClusteredError(sourceId));
305
+ return;
306
+ }
307
+ source.getClusterExpansionZoom(clusterId, (error, expansionZoom) => {
308
+ if (error) {
309
+ reject(error);
310
+ }
311
+ else if (typeof expansionZoom !== 'number') {
312
+ reject(new Error(`Cluster ${clusterId} in source '${sourceId}' gave no expansion zoom.`));
313
+ }
314
+ else {
315
+ resolve(expansionZoom);
316
+ }
317
+ });
318
+ });
319
+ }
320
+ /**
321
+ * Features rendered at a screen point or in a `[corner, corner]` box (the whole viewport when `geometry` is
322
+ * undefined), kept to `layers` and `filter`. Returns `[]` when the map has not been initialised yet.
323
+ */
324
+ getRenderedFeatures(geometry, query) {
325
+ return this.map ? this.map.queryRenderedFeatures(geometry, query) : [];
326
+ }
327
+ /** Whether `lngLat` projects inside the canvas, `insets` pixels in from its edges. False before the map exists. */
328
+ isPointOnScreen(lngLat, insets = 0) {
329
+ if (!this.mapInitialised) {
330
+ return false;
331
+ }
332
+ const point = this.map.project(lngLat);
333
+ const canvas = this.map.getCanvas();
334
+ return point.x >= this.insetOf(insets, 'left')
335
+ && point.y >= this.insetOf(insets, 'top')
336
+ && point.x <= canvas.clientWidth - this.insetOf(insets, 'right')
337
+ && point.y <= canvas.clientHeight - this.insetOf(insets, 'bottom');
338
+ }
339
+ /** Whether the shared map is on screen inside `element`: its active container is `element` or below it. */
340
+ isShownIn(element) {
341
+ const active = this._activeContainer();
342
+ return active !== null && element.contains(active);
299
343
  }
300
- /** Swap the base style. Custom sources/layers you added must be re-applied after `styledata`. */
301
- setStyle(styleUrl) {
344
+ /**
345
+ * Swap the base style. `{ diff: false }` rebuilds it from scratch, for a swap where mapbox's diff keeps a source the
346
+ * rebuild then trips over. Custom sources/layers you added must be re-applied after `styledata`.
347
+ */
348
+ setStyle(styleUrl, options) {
302
349
  const cachedStyle = styleCache.get(styleUrl);
303
- this.map.setStyle((cachedStyle ?? styleUrl));
350
+ // The typings mark mapbox's optional font options as required.
351
+ this.map.setStyle((cachedStyle ?? styleUrl), options);
304
352
  if (!cachedStyle) {
305
353
  this.map.once('style.load', () => {
306
354
  styleCache.set(styleUrl, this.map.getStyle());
307
355
  });
308
356
  }
309
357
  }
310
- /** Animate the camera to `center` at the given zoom (default 13). */
358
+ /** Animate the camera to `center` at the given zoom (default 13). `flyTo` takes a duration, a curve and event data. */
311
359
  moveCenter(center, zoom = 13) {
312
360
  this.map.flyTo({ center, zoom });
313
361
  }
314
- /** Fit the viewport to `bounds` with optional pixel padding (default 40). */
315
- fitBounds(bounds, padding = 40) {
316
- this.map.fitBounds(bounds, { padding, duration: 1000 });
362
+ /**
363
+ * Fit the viewport to `bounds`. A number is the padding (default 40) of a one-second slide; options (`padding` per
364
+ * side, `maxZoom`, `duration`, `animate: false`, …) lay over those same defaults. `eventData` reaches the move's events.
365
+ */
366
+ fitBounds(bounds, options = {}, eventData) {
367
+ const overrides = typeof options === 'number' ? { padding: options } : options;
368
+ this.map.fitBounds(bounds, { ...this.fitDefaults, ...overrides }, eventData);
369
+ }
370
+ /** Fly the camera (mapbox's `flyTo`: `center`, `zoom`, `duration`, `curve`, `offset`, …). */
371
+ flyTo(options, eventData) {
372
+ this.map.flyTo(options, eventData);
373
+ }
374
+ /** Ease the camera (mapbox's `easeTo`), e.g. into a cluster's expansion zoom. */
375
+ easeTo(options, eventData) {
376
+ this.map.easeTo(options, eventData);
377
+ }
378
+ /** Move the camera at once (mapbox's `jumpTo`). */
379
+ jumpTo(options, eventData) {
380
+ this.map.jumpTo(options, eventData);
381
+ }
382
+ /**
383
+ * Have mapbox re-read its container's size, e.g. from a `ResizeObserver`. A resize fires `movestart` / `moveend`, which
384
+ * carry `eventData`. No-op before the map exists.
385
+ */
386
+ resize(eventData) {
387
+ if (this.mapInitialised) {
388
+ this.map.resize(eventData);
389
+ }
317
390
  }
318
391
  /**
319
392
  * Add a GeoJSON source. Pass `clustered: true` and optional `clusterRadius`/`clusterMaxZoom`
@@ -338,6 +411,18 @@ class MapboxService {
338
411
  }
339
412
  this.map.addSource(config.id, src);
340
413
  }
414
+ /**
415
+ * Add a GeoJSON source, or replace the data of the one already under `config.id` (its other options stay as they
416
+ * were). True when it was added, so the caller adds the layers that draw it.
417
+ */
418
+ upsertSource(config) {
419
+ if (this.hasSource(config.id)) {
420
+ this.updateSource(config.id, config.data);
421
+ return false;
422
+ }
423
+ this.addSource(config);
424
+ return true;
425
+ }
341
426
  /** Replace the data of an existing GeoJSON source in place. No-op if the source is missing. */
342
427
  updateSource(id, data) {
343
428
  const source = this.map.getSource(id);
@@ -431,6 +516,12 @@ class MapboxService {
431
516
  getLayerIds() {
432
517
  return this.map.getStyle().layers.map((l) => l.id);
433
518
  }
519
+ /** Move a layer to the top, or just under `beforeId`. No-op when the layer is missing. */
520
+ moveLayer(id, beforeId) {
521
+ if (this.hasLayer(id)) {
522
+ this.map.moveLayer(id, beforeId);
523
+ }
524
+ }
434
525
  /** `true` when a layer with this id exists in the current style. */
435
526
  hasLayer(id) {
436
527
  return !!this.map.getLayer(id);
@@ -514,9 +605,9 @@ class MapboxService {
514
605
  * Enter polygon-drawing mode. Lazily mounts a `@mapbox/mapbox-gl-draw` control,
515
606
  * hides its default UI (consumer controls the toggle), and switches to `draw_polygon`.
516
607
  * The user clicks vertices and double-clicks (or clicks the first vertex) to close.
517
- * The completed polygon is emitted on `polygonCreate`.
608
+ * The completed polygon is emitted on `polygonCreate`. `keepPanZoom` leaves drag and zoom on.
518
609
  */
519
- enableDrawPolygon() {
610
+ enableDrawPolygon(options) {
520
611
  if (!this.draw) {
521
612
  this.draw = new MapboxDraw({
522
613
  displayControlsDefault: false,
@@ -533,9 +624,16 @@ class MapboxService {
533
624
  };
534
625
  this.map.on('draw.create', this.onDrawCreate);
535
626
  }
536
- this.lockInteractions();
627
+ this.lockInteractions(options?.keepPanZoom === true);
537
628
  this.draw.changeMode('draw_polygon');
538
629
  }
630
+ /**
631
+ * Close the polygon being drawn, as a double-click would: it is emitted on `polygonCreate` when it has three corners
632
+ * or more. Draw mode (and its gesture lock) stays until `disableDrawPolygon`. No-op when not drawing.
633
+ */
634
+ finishDrawPolygon() {
635
+ this.draw?.changeMode('simple_select');
636
+ }
539
637
  /** Exit polygon-drawing mode and remove any in-progress or drawn polygons. */
540
638
  disableDrawPolygon() {
541
639
  if (this.onDrawCreate) {
@@ -550,12 +648,12 @@ class MapboxService {
550
648
  this.unlockInteractions();
551
649
  }
552
650
  /**
553
- * Disable pan/zoom handlers so the viewport stays fixed while the user draws.
554
- * Saves the prior enabled-state for each handler so it can be restored by
651
+ * Disable pan/zoom handlers so the viewport stays fixed while the user draws (drag, wheel and pinch stay on with
652
+ * `keepPanZoom`). Saves the prior enabled-state for each handler so it can be restored by
555
653
  * `unlockInteractions`. Safe to call repeatedly — a second call is a no-op
556
654
  * because saved state is only captured on the first lock.
557
655
  */
558
- lockInteractions() {
656
+ lockInteractions(keepPanZoom) {
559
657
  if (this.savedInteractions) {
560
658
  return;
561
659
  }
@@ -567,11 +665,13 @@ class MapboxService {
567
665
  touchZoomRotate: this.map.touchZoomRotate.isEnabled(),
568
666
  keyboard: this.map.keyboard.isEnabled(),
569
667
  };
570
- this.map.dragPan.disable();
571
- this.map.scrollZoom.disable();
668
+ if (!keepPanZoom) {
669
+ this.map.dragPan.disable();
670
+ this.map.scrollZoom.disable();
671
+ this.map.touchZoomRotate.disable();
672
+ }
572
673
  this.map.boxZoom.disable();
573
674
  this.map.doubleClickZoom.disable();
574
- this.map.touchZoomRotate.disable();
575
675
  this.map.keyboard.disable();
576
676
  }
577
677
  /**
@@ -601,6 +701,17 @@ class MapboxService {
601
701
  clearDrawnPolygons() {
602
702
  this.draw?.deleteAll();
603
703
  }
704
+ // The GeoJSON source under `sourceId` (it has the cluster calls), or null when it is missing or another kind.
705
+ clusterSourceOf(sourceId) {
706
+ const source = this.map.getSource(sourceId);
707
+ return source && typeof source.getClusterLeaves === 'function' ? source : null;
708
+ }
709
+ notClusteredError(sourceId) {
710
+ return new Error(`Source '${sourceId}' is not a clustered GeoJSON source or is missing.`);
711
+ }
712
+ insetOf(insets, side) {
713
+ return typeof insets === 'number' ? insets : insets[side] ?? 0;
714
+ }
604
715
  /** `isStyleLoaded()` also waits for tiles; what addSource needs is mapbox's one-shot "style parsed" flag. */
605
716
  isStyleParsed() {
606
717
  return this.map.isStyleLoaded() || !!this.map.style?._loaded;
@@ -691,48 +802,157 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.1", ngImpor
691
802
  args: [{ selector: 'apex-map', standalone: true, changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, template: "<div #container class=\"apex-map__container\"></div>\n", styles: [":host{display:block;width:100%;height:100%}.apex-map__container{width:100%;height:100%}\n"] }]
692
803
  }], ctorParameters: () => [], propDecorators: { center: [{ type: i0.Input, args: [{ isSignal: true, alias: "center", required: false }] }], zoom: [{ type: i0.Input, args: [{ isSignal: true, alias: "zoom", required: false }] }], mapStyle: [{ type: i0.Input, args: [{ isSignal: true, alias: "mapStyle", required: false }] }], maxBounds: [{ type: i0.Input, args: [{ isSignal: true, alias: "maxBounds", required: false }] }], showNavigation: [{ type: i0.Input, args: [{ isSignal: true, alias: "showNavigation", required: false }] }], mapReady: [{ type: i0.Output, args: ["mapReady"] }], mapClick: [{ type: i0.Output, args: ["mapClick"] }], featureClick: [{ type: i0.Output, args: ["featureClick"] }], container: [{ type: i0.ViewChild, args: ['container', { isSignal: true }] }] } });
693
804
 
805
+ /**
806
+ * A trackpad pinch arrives as a ctrl+wheel. Over anything laid on the map (a card, the map's buttons, a legend, a top
807
+ * bar) it would zoom the page; this hands it to the shared map under it instead. Put it on the overlay itself, or on a
808
+ * container holding the map and its overlays.
809
+ */
810
+ class ApexMapPinchZoomDirective {
811
+ constructor() {
812
+ this.host = inject(ElementRef);
813
+ this.map = inject(MapboxService);
814
+ this.onWheel = (event) => {
815
+ // Taken already (mapbox over its own canvas, an overlay nested in this one), or our own re-dispatch (untrusted).
816
+ if (!event.ctrlKey || !event.isTrusted || event.defaultPrevented || !this.holdsShownMap()) {
817
+ return;
818
+ }
819
+ const rawMap = this.map.getMap();
820
+ if (!rawMap?.scrollZoom.isEnabled()) {
821
+ return;
822
+ }
823
+ // Only over the map itself, measured on its container: the canvas container mapbox listens on has no height.
824
+ const rect = rawMap.getContainer().getBoundingClientRect();
825
+ if (event.clientX < rect.left || event.clientX > rect.right || event.clientY < rect.top || event.clientY > rect.bottom) {
826
+ return;
827
+ }
828
+ event.preventDefault();
829
+ rawMap.getCanvasContainer().dispatchEvent(new WheelEvent('wheel', {
830
+ bubbles: true,
831
+ cancelable: true,
832
+ ctrlKey: true,
833
+ shiftKey: event.shiftKey,
834
+ clientX: event.clientX,
835
+ clientY: event.clientY,
836
+ deltaX: event.deltaX,
837
+ deltaY: event.deltaY,
838
+ deltaMode: event.deltaMode,
839
+ }));
840
+ };
841
+ // Not passive, so the pinch can stop the page from zooming.
842
+ this.host.nativeElement.addEventListener('wheel', this.onWheel, { passive: false });
843
+ }
844
+ /** Stops listening. */
845
+ ngOnDestroy() {
846
+ this.host.nativeElement.removeEventListener('wheel', this.onWheel);
847
+ }
848
+ // The one map moves between surfaces: zoom it only while it is shown inside this element (a container) or inside the
849
+ // element this one is positioned in (a card anchored over the map).
850
+ holdsShownMap() {
851
+ const host = this.host.nativeElement;
852
+ const anchor = host.offsetParent;
853
+ return this.map.isShownIn(host) || (anchor !== null && this.map.isShownIn(anchor));
854
+ }
855
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.1", ngImport: i0, type: ApexMapPinchZoomDirective, deps: [], target: i0.ɵɵFactoryTarget.Directive }); }
856
+ static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "21.2.1", type: ApexMapPinchZoomDirective, isStandalone: true, selector: "[apexMapPinchZoom]", ngImport: i0 }); }
857
+ }
858
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.1", ngImport: i0, type: ApexMapPinchZoomDirective, decorators: [{
859
+ type: Directive,
860
+ args: [{
861
+ selector: '[apexMapPinchZoom]',
862
+ standalone: true,
863
+ }]
864
+ }], ctorParameters: () => [] });
865
+
866
+ /**
867
+ * The reader's location as a dot on the map, in the consumer's `style`, and the camera move to it at the consumer's
868
+ * `zoom`. Not injectable: a map surface builds one with the `MapboxService` it draws on, repaints it after a style swap
869
+ * and destroys it on teardown.
870
+ */
871
+ class MapUserLocationLayer {
872
+ constructor(map, config) {
873
+ this.map = map;
874
+ /** The last location read, as `[lng, lat]`; null until one is. */
875
+ this.location = signal(null, ...(ngDevMode ? [{ debugName: "location" }] : []));
876
+ this.sourceId = config.sourceId ?? 'user-location';
877
+ this.layerId = config.layerId ?? 'user-location-dot';
878
+ this.zoom = config.zoom;
879
+ this.style = { ...config.style };
880
+ }
881
+ /** Reads the location once and draws the dot; the camera stays where it is. */
882
+ async init(options) {
883
+ const result = await MapGeolocationUtil.locate(options);
884
+ if (result.status === 'located') {
885
+ this.location.set(result.position);
886
+ this.repaint();
887
+ }
888
+ return result;
889
+ }
890
+ /** Flies to the location (at the configured zoom), reading it first when none is known yet. */
891
+ async locate(options) {
892
+ const known = this.location();
893
+ if (known) {
894
+ this.map.moveCenter(known, this.zoom);
895
+ return { status: 'located', position: known };
896
+ }
897
+ const result = await this.init(options);
898
+ if (result.status === 'located') {
899
+ this.map.moveCenter(result.position, this.zoom);
900
+ }
901
+ return result;
902
+ }
903
+ /** Puts the dot (back) on the map, e.g. after a style swap. No-op until a location is known. */
904
+ repaint() {
905
+ const position = this.location();
906
+ if (!position) {
907
+ return;
908
+ }
909
+ this.map.upsertSource({ id: this.sourceId, data: this.pointOf(position) });
910
+ if (this.map.hasLayer(this.layerId)) {
911
+ return;
912
+ }
913
+ this.map.addLayer({
914
+ id: this.layerId,
915
+ type: 'circle',
916
+ source: this.sourceId,
917
+ paint: {
918
+ 'circle-radius': this.style.circleRadius,
919
+ 'circle-color': this.style.circleColor,
920
+ 'circle-stroke-color': this.style.strokeColor,
921
+ 'circle-stroke-width': this.style.strokeWidth,
922
+ },
923
+ });
924
+ }
925
+ /** Takes the dot off the map; the location is kept for the next `repaint`. */
926
+ destroy() {
927
+ this.map.safeRemoveLayer(this.layerId);
928
+ if (this.map.hasSource(this.sourceId)) {
929
+ this.map.removeSource(this.sourceId);
930
+ }
931
+ }
932
+ pointOf(position) {
933
+ return {
934
+ type: 'FeatureCollection',
935
+ features: [{ type: 'Feature', geometry: { type: 'Point', coordinates: position }, properties: {} }],
936
+ };
937
+ }
938
+ }
939
+
694
940
  /**
695
941
  * Recursively flatten any nesting of GeoJSON coordinates down to a flat list of [lng, lat] pairs.
696
942
  * Handles Point, LineString, Polygon, and MultiPolygon coordinate shapes uniformly.
697
943
  */
698
944
  function flattenCoords(arr) {
699
945
  const out = [];
700
- const recurse = (node) => {
701
- if (Array.isArray(node) &&
702
- typeof node[0] === 'number' &&
703
- typeof node[1] === 'number') {
704
- out.push(node);
705
- }
706
- else if (Array.isArray(node)) {
707
- node.forEach(recurse);
708
- }
709
- };
710
- recurse(arr);
946
+ MapGeometryUtil.forEachPosition(arr, (position) => out.push(position));
711
947
  return out;
712
948
  }
713
949
  /**
714
- * Compute the [[minLng, minLat], [maxLng, maxLat]] bounds of a flat list of coordinates.
715
- * Return value is compatible with `mapboxgl.LngLatBoundsLike`.
950
+ * Compute the [[minLng, minLat], [maxLng, maxLat]] bounds of a flat list of coordinates, compatible with
951
+ * `mapboxgl.LngLatBoundsLike`. `wrapAntimeridian` frames a shape across ±180° by its narrower side. No coordinates give
952
+ * `[[180, 90], [-180, -90]]`. For whole GeoJSON, `MapGeometryUtil.boundsOf` walks it without flattening.
716
953
  */
717
- function calculateBounds(coords) {
718
- let minX = 180;
719
- let minY = 90;
720
- let maxX = -180;
721
- let maxY = -90;
722
- coords.forEach(([lng, lat]) => {
723
- if (lng < minX)
724
- minX = lng;
725
- if (lng > maxX)
726
- maxX = lng;
727
- if (lat < minY)
728
- minY = lat;
729
- if (lat > maxY)
730
- maxY = lat;
731
- });
732
- return [
733
- [minX, minY],
734
- [maxX, maxY],
735
- ];
954
+ function calculateBounds(coords, options) {
955
+ return MapGeometryUtil.boundsOf({ type: 'MultiPoint', coordinates: coords }, options) ?? [[180, 90], [-180, -90]];
736
956
  }
737
957
  /**
738
958
  * Build a closed square polygon of side `2 * radiusKm` centered at `center`.
@@ -760,5 +980,5 @@ function calculateViewportPolygonFromCenter(center, radiusKm = 0.5) {
760
980
  * Generated bundle index. Do not edit.
761
981
  */
762
982
 
763
- export { ApexMapComponent, MapboxService, calculateBounds, calculateViewportPolygonFromCenter, flattenCoords };
983
+ export { ApexMapComponent, ApexMapPinchZoomDirective, MapUserLocationLayer, MapboxService, calculateBounds, calculateViewportPolygonFromCenter, flattenCoords };
764
984
  //# sourceMappingURL=apexara-map.mjs.map