@apexara/map 1.0.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 +428 -0
- package/fesm2022/apexara-map.mjs +720 -0
- package/fesm2022/apexara-map.mjs.map +1 -0
- package/package.json +42 -0
- package/types/apexara-map.d.ts +307 -0
|
@@ -0,0 +1,720 @@
|
|
|
1
|
+
import { isPlatformBrowser } from '@angular/common';
|
|
2
|
+
import * as i0 from '@angular/core';
|
|
3
|
+
import { InjectionToken, makeEnvironmentProviders, signal, inject, PLATFORM_ID, Injectable, input, output, DestroyRef, viewChild, effect, ViewEncapsulation, ChangeDetectionStrategy, Component } from '@angular/core';
|
|
4
|
+
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
|
5
|
+
import { Subject } from 'rxjs';
|
|
6
|
+
import MapboxDraw from '@mapbox/mapbox-gl-draw';
|
|
7
|
+
import mapboxgl from 'mapbox-gl';
|
|
8
|
+
|
|
9
|
+
const MAP_CONFIG = new InjectionToken('APEX_MAP_CONFIG');
|
|
10
|
+
/**
|
|
11
|
+
* Register @apexara/map at the application root.
|
|
12
|
+
*
|
|
13
|
+
* @example
|
|
14
|
+
* // app.config.ts
|
|
15
|
+
* providers: [
|
|
16
|
+
* provideMap({ accessToken: environment.mapboxToken }),
|
|
17
|
+
* ]
|
|
18
|
+
*/
|
|
19
|
+
function provideMap(config) {
|
|
20
|
+
return makeEnvironmentProviders([{ provide: MAP_CONFIG, useValue: config }]);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
var MapStyles;
|
|
24
|
+
(function (MapStyles) {
|
|
25
|
+
MapStyles["Sat"] = "mapbox://styles/mapbox/satellite-streets-v12";
|
|
26
|
+
MapStyles["Streets"] = "mapbox://styles/mapbox/streets-v12";
|
|
27
|
+
MapStyles["DarkV11"] = "mapbox://styles/mapbox/dark-v11";
|
|
28
|
+
MapStyles["LightV11"] = "mapbox://styles/mapbox/light-v11";
|
|
29
|
+
MapStyles["OutdoorsV12"] = "mapbox://styles/mapbox/outdoors-v12";
|
|
30
|
+
})(MapStyles || (MapStyles = {}));
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Mapbox Service — wrapper around a `mapboxgl.Map` instance.
|
|
34
|
+
*
|
|
35
|
+
* Terms:
|
|
36
|
+
* - Feature: A GeoJSON geometry (Point/LineString/Polygon/…) drawn on the map.
|
|
37
|
+
* - Properties: Arbitrary key-value pairs on `feature.properties`.
|
|
38
|
+
* - Source: Raw data (GeoJSON, vector tiles, raster tiles) added with `addSource`.
|
|
39
|
+
* - Layer: A visual rendering (circle, fill, heatmap, raster, …) bound to a source.
|
|
40
|
+
* - Cluster: A grouped feature emitted when `cluster: true` is set on a GeoJSON source.
|
|
41
|
+
*
|
|
42
|
+
* Browser-only: `init()` is a no-op on the server. Methods other than `init()` assume
|
|
43
|
+
* the map instance exists and must only be called after `ready()` becomes true.
|
|
44
|
+
*/
|
|
45
|
+
// Process-lifetime cache of parsed Mapbox style JSON keyed by URL. Subsequent
|
|
46
|
+
// inits with the same URL pass the cached object to the Map constructor
|
|
47
|
+
// instead of re-fetching `api.mapbox.com/styles/v1/...`.
|
|
48
|
+
const styleCache = new Map();
|
|
49
|
+
class MapboxService {
|
|
50
|
+
constructor() {
|
|
51
|
+
/** Click on empty canvas (no features under the cursor). Event stream. */
|
|
52
|
+
this.mapClick = new Subject();
|
|
53
|
+
/** Click on a feature (wired by consumers via `on('click', layerId, ...)`). Event stream. */
|
|
54
|
+
this.featureClick = new Subject();
|
|
55
|
+
/** Fires when the user completes a polygon in draw mode (double-click or first-vertex click). */
|
|
56
|
+
this.polygonCreate = new Subject();
|
|
57
|
+
this._ready = signal(false, ...(ngDevMode ? [{ debugName: "_ready" }] : []));
|
|
58
|
+
/** Reactive state: `true` once the map's `load` event has fired. */
|
|
59
|
+
this.ready = this._ready;
|
|
60
|
+
/** Reactive state: current center `[lng, lat]`. Updates on `moveend`. `null` before init. */
|
|
61
|
+
this.center = signal(null, ...(ngDevMode ? [{ debugName: "center" }] : []));
|
|
62
|
+
/** Reactive state: current zoom level. Updates on `moveend`. `null` before init. */
|
|
63
|
+
this.zoom = signal(null, ...(ngDevMode ? [{ debugName: "zoom" }] : []));
|
|
64
|
+
/** Reactive state: current viewport bounds `[[swLng, swLat], [neLng, neLat]]`. Updates on `moveend`. */
|
|
65
|
+
this.bounds = signal(null, ...(ngDevMode ? [{ debugName: "bounds" }] : []));
|
|
66
|
+
/** Reactive state: `true` while the map is panning/zooming (between `movestart` and `moveend`). */
|
|
67
|
+
this.isMoving = signal(false, ...(ngDevMode ? [{ debugName: "isMoving" }] : []));
|
|
68
|
+
// `map` stays non-null-typed so existing call-sites don't need guards;
|
|
69
|
+
// this flag tracks whether the constructor has actually run.
|
|
70
|
+
this.mapInitialised = false;
|
|
71
|
+
this.config = inject(MAP_CONFIG);
|
|
72
|
+
this.platformId = inject(PLATFORM_ID);
|
|
73
|
+
// mapbox-gl is given this stable element (not the consumer's `<div>`).
|
|
74
|
+
// The service re-parents `hostDiv` between consumer containers on context
|
|
75
|
+
// swaps so the underlying `mapboxgl.Map` survives → one billed load per session.
|
|
76
|
+
this.hostDiv = null;
|
|
77
|
+
this.containerStack = [];
|
|
78
|
+
this._activeContainer = signal(null, ...(ngDevMode ? [{ debugName: "_activeContainer" }] : []));
|
|
79
|
+
this.activeContainer = this._activeContainer;
|
|
80
|
+
}
|
|
81
|
+
/** Back-compat wrapper around `activate`. SSR-safe. */
|
|
82
|
+
async init(options) {
|
|
83
|
+
if (!isPlatformBrowser(this.platformId)) {
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
this.activate(options.container, options);
|
|
87
|
+
}
|
|
88
|
+
activate(container, options) {
|
|
89
|
+
if (!isPlatformBrowser(this.platformId)) {
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
if (!this.mapInitialised) {
|
|
93
|
+
this.createMap(container, options);
|
|
94
|
+
this.containerStack.push(container);
|
|
95
|
+
this._activeContainer.set(container);
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
const active = this._activeContainer();
|
|
99
|
+
if (active === container) {
|
|
100
|
+
if (options.center) {
|
|
101
|
+
this.map.jumpTo({ center: options.center, zoom: options.zoom ?? this.map.getZoom() });
|
|
102
|
+
}
|
|
103
|
+
requestAnimationFrame(() => this.map.resize());
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
this.hostDiv?.remove();
|
|
107
|
+
if (this.hostDiv) {
|
|
108
|
+
this.hostDiv.style.display = '';
|
|
109
|
+
container.appendChild(this.hostDiv);
|
|
110
|
+
}
|
|
111
|
+
this.containerStack = this.containerStack.filter((c) => c !== container);
|
|
112
|
+
this.containerStack.push(container);
|
|
113
|
+
this._activeContainer.set(container);
|
|
114
|
+
if (options.center) {
|
|
115
|
+
this.map.jumpTo({ center: options.center, zoom: options.zoom ?? this.map.getZoom() });
|
|
116
|
+
}
|
|
117
|
+
requestAnimationFrame(() => this.map.resize());
|
|
118
|
+
}
|
|
119
|
+
deactivate(container) {
|
|
120
|
+
if (!isPlatformBrowser(this.platformId)) {
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
const wasActive = this._activeContainer() === container;
|
|
124
|
+
this.containerStack = this.containerStack.filter((c) => c !== container);
|
|
125
|
+
if (!wasActive) {
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
const next = this.containerStack[this.containerStack.length - 1];
|
|
129
|
+
this.hostDiv?.remove();
|
|
130
|
+
if (next && this.hostDiv) {
|
|
131
|
+
this.hostDiv.style.display = '';
|
|
132
|
+
next.appendChild(this.hostDiv);
|
|
133
|
+
this._activeContainer.set(next);
|
|
134
|
+
requestAnimationFrame(() => this.map.resize());
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
if (this.hostDiv) {
|
|
138
|
+
document.body.appendChild(this.hostDiv);
|
|
139
|
+
this.hostDiv.style.display = 'none';
|
|
140
|
+
}
|
|
141
|
+
this._activeContainer.set(null);
|
|
142
|
+
}
|
|
143
|
+
createMap(container, options) {
|
|
144
|
+
const defaultBounds = [
|
|
145
|
+
[-175, -85],
|
|
146
|
+
[175, 85],
|
|
147
|
+
];
|
|
148
|
+
const styleInput = options.mapStyle || this.config.defaultStyle || MapStyles.Streets;
|
|
149
|
+
const styleUrl = typeof styleInput === 'string' ? styleInput : null;
|
|
150
|
+
const cachedStyle = styleUrl ? styleCache.get(styleUrl) : undefined;
|
|
151
|
+
this.hostDiv = document.createElement('div');
|
|
152
|
+
this.hostDiv.style.cssText = 'position:absolute;inset:0;width:100%;height:100%;';
|
|
153
|
+
container.appendChild(this.hostDiv);
|
|
154
|
+
this.map = new mapboxgl.Map({
|
|
155
|
+
center: options.center,
|
|
156
|
+
zoom: options.zoom || 10,
|
|
157
|
+
accessToken: this.config.accessToken,
|
|
158
|
+
container: this.hostDiv,
|
|
159
|
+
style: (cachedStyle ?? styleInput),
|
|
160
|
+
fadeDuration: 0,
|
|
161
|
+
pitch: 0,
|
|
162
|
+
bearing: 0,
|
|
163
|
+
dragRotate: false,
|
|
164
|
+
pitchWithRotate: false,
|
|
165
|
+
projection: 'mercator',
|
|
166
|
+
maxBounds: options.maxBounds ?? defaultBounds,
|
|
167
|
+
renderWorldCopies: false,
|
|
168
|
+
// Required for `canvas.toDataURL()` to return pixels — consumers that
|
|
169
|
+
// snapshot the canvas (e.g. freeze-frame overlays) rely on this.
|
|
170
|
+
preserveDrawingBuffer: true,
|
|
171
|
+
});
|
|
172
|
+
this.mapInitialised = true;
|
|
173
|
+
if (styleUrl && !cachedStyle) {
|
|
174
|
+
this.map.once('style.load', () => {
|
|
175
|
+
styleCache.set(styleUrl, this.map.getStyle());
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
this.center.set(options.center);
|
|
179
|
+
this.zoom.set(options.zoom ?? 10);
|
|
180
|
+
this.map.on('movestart', () => this.isMoving.set(true));
|
|
181
|
+
this.map.on('moveend', () => {
|
|
182
|
+
const c = this.map.getCenter();
|
|
183
|
+
const b = this.map.getBounds();
|
|
184
|
+
const sw = b.getSouthWest();
|
|
185
|
+
const ne = b.getNorthEast();
|
|
186
|
+
this.center.set([c.lng, c.lat]);
|
|
187
|
+
this.zoom.set(this.map.getZoom());
|
|
188
|
+
this.bounds.set([[sw.lng, sw.lat], [ne.lng, ne.lat]]);
|
|
189
|
+
this.isMoving.set(false);
|
|
190
|
+
});
|
|
191
|
+
this.map.once('load', () => {
|
|
192
|
+
if (options.showNavigation !== false) {
|
|
193
|
+
this.map.addControl(new mapboxgl.NavigationControl({ showCompass: false, showZoom: true }));
|
|
194
|
+
}
|
|
195
|
+
this._ready.set(true);
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
/** Current map center as a `LngLat`. Prefer the `center` signal for reactive reads. */
|
|
199
|
+
getCenter() {
|
|
200
|
+
return this.map.getCenter();
|
|
201
|
+
}
|
|
202
|
+
/** Current zoom level. Prefer the `zoom` signal for reactive reads. */
|
|
203
|
+
getZoom() {
|
|
204
|
+
return this.map.getZoom();
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* Return the current viewport as a closed GeoJSON-style polygon ring
|
|
208
|
+
* (`[sw, se, ne, nw, sw]`). Useful for point-in-polygon queries against the
|
|
209
|
+
* visible area.
|
|
210
|
+
*/
|
|
211
|
+
getViewportPolygon() {
|
|
212
|
+
const bounds = this.map.getBounds();
|
|
213
|
+
const sw = bounds.getSouthWest();
|
|
214
|
+
const se = bounds.getSouthEast();
|
|
215
|
+
const ne = bounds.getNorthEast();
|
|
216
|
+
const nw = bounds.getNorthWest();
|
|
217
|
+
return [
|
|
218
|
+
[
|
|
219
|
+
[sw.lng, sw.lat],
|
|
220
|
+
[se.lng, se.lat],
|
|
221
|
+
[ne.lng, ne.lat],
|
|
222
|
+
[nw.lng, nw.lat],
|
|
223
|
+
[sw.lng, sw.lat],
|
|
224
|
+
],
|
|
225
|
+
];
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* Extract `properties` from the first feature under a click/hover event,
|
|
229
|
+
* cast to `T`. Returns `undefined` when no feature was hit or it has no props.
|
|
230
|
+
*/
|
|
231
|
+
getFeatureProperties(mouseEvent) {
|
|
232
|
+
const feature = mouseEvent.features?.[0];
|
|
233
|
+
if (!feature) {
|
|
234
|
+
return undefined;
|
|
235
|
+
}
|
|
236
|
+
const properties = feature.properties;
|
|
237
|
+
if (!properties) {
|
|
238
|
+
return undefined;
|
|
239
|
+
}
|
|
240
|
+
return properties;
|
|
241
|
+
}
|
|
242
|
+
/**
|
|
243
|
+
* Expand a cluster into its individual leaf features (up to `limit`, paginated
|
|
244
|
+
* via `offset`). Rejects if `sourceId` is missing or not a clustered GeoJSON source.
|
|
245
|
+
*/
|
|
246
|
+
async getClusterProperties(sourceId, clusterId, limit = 10000, offset = 0) {
|
|
247
|
+
return new Promise((resolve, reject) => {
|
|
248
|
+
const src = this.map.getSource(sourceId);
|
|
249
|
+
if (!src || typeof src.getClusterLeaves !== 'function') {
|
|
250
|
+
reject(new Error(`Source '${sourceId}' is not a clustered GeoJSON source or is missing.`));
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
src.getClusterLeaves(clusterId, limit, offset, (err, features) => {
|
|
254
|
+
if (err) {
|
|
255
|
+
reject(err);
|
|
256
|
+
}
|
|
257
|
+
else {
|
|
258
|
+
resolve(features);
|
|
259
|
+
}
|
|
260
|
+
});
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* Query features rendered at a screen point, optionally restricted to specific layers.
|
|
265
|
+
* Returns `[]` when the map has not been initialised yet.
|
|
266
|
+
*/
|
|
267
|
+
getRenderedFeatures(point, params) {
|
|
268
|
+
return this.map ? this.map.queryRenderedFeatures(point, params) : [];
|
|
269
|
+
}
|
|
270
|
+
/** Swap the base style. Custom sources/layers you added must be re-applied after `styledata`. */
|
|
271
|
+
setStyle(styleUrl) {
|
|
272
|
+
const cachedStyle = styleCache.get(styleUrl);
|
|
273
|
+
this.map.setStyle((cachedStyle ?? styleUrl));
|
|
274
|
+
if (!cachedStyle) {
|
|
275
|
+
this.map.once('style.load', () => {
|
|
276
|
+
styleCache.set(styleUrl, this.map.getStyle());
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
/** Animate the camera to `center` at the given zoom (default 13). */
|
|
281
|
+
moveCenter(center, zoom = 13) {
|
|
282
|
+
this.map.flyTo({ center, zoom });
|
|
283
|
+
}
|
|
284
|
+
/** Fit the viewport to `bounds` with optional pixel padding (default 40). */
|
|
285
|
+
fitBounds(bounds, padding = 40) {
|
|
286
|
+
this.map.fitBounds(bounds, { padding, duration: 1000 });
|
|
287
|
+
}
|
|
288
|
+
/**
|
|
289
|
+
* Add a GeoJSON source. Pass `clustered: true` and optional `clusterRadius`/`clusterMaxZoom`
|
|
290
|
+
* for point clustering. Set `generateId: true` when you plan to use feature-state.
|
|
291
|
+
*/
|
|
292
|
+
addSource(config) {
|
|
293
|
+
const src = {
|
|
294
|
+
type: 'geojson',
|
|
295
|
+
data: config.data,
|
|
296
|
+
};
|
|
297
|
+
if (config.clustered !== undefined) {
|
|
298
|
+
src.cluster = config.clustered;
|
|
299
|
+
}
|
|
300
|
+
if (config.clusterRadius !== undefined) {
|
|
301
|
+
src.clusterRadius = config.clusterRadius;
|
|
302
|
+
}
|
|
303
|
+
if (config.clusterMaxZoom !== undefined) {
|
|
304
|
+
src.clusterMaxZoom = config.clusterMaxZoom;
|
|
305
|
+
}
|
|
306
|
+
if (config.generateId !== undefined) {
|
|
307
|
+
src.generateId = config.generateId;
|
|
308
|
+
}
|
|
309
|
+
this.map.addSource(config.id, src);
|
|
310
|
+
}
|
|
311
|
+
/** Replace the data of an existing GeoJSON source in place. No-op if the source is missing. */
|
|
312
|
+
updateSource(id, data) {
|
|
313
|
+
const source = this.map.getSource(id);
|
|
314
|
+
if (source && 'setData' in source) {
|
|
315
|
+
source.setData(data);
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
/**
|
|
319
|
+
* Add a layer to the style. Pass `beforeId` to insert the new layer beneath
|
|
320
|
+
* an existing one (useful for controlling draw order against style layers).
|
|
321
|
+
*/
|
|
322
|
+
addLayer(layer, beforeId) {
|
|
323
|
+
if (beforeId) {
|
|
324
|
+
this.map.addLayer(layer, beforeId);
|
|
325
|
+
}
|
|
326
|
+
else {
|
|
327
|
+
this.map.addLayer(layer);
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
/**
|
|
331
|
+
* Add a raster layer backed by a source with the same id. Starts hidden —
|
|
332
|
+
* toggle with `toggleLayerVisibility(id)` or `setLayoutProperty`.
|
|
333
|
+
*/
|
|
334
|
+
addRasterLayer(id, _url) {
|
|
335
|
+
this.map.addLayer({
|
|
336
|
+
id,
|
|
337
|
+
type: 'raster',
|
|
338
|
+
source: id,
|
|
339
|
+
layout: { visibility: 'none' },
|
|
340
|
+
});
|
|
341
|
+
}
|
|
342
|
+
/** Add a vector tile source from a TileJSON URL (typically `mapbox://...`). */
|
|
343
|
+
addVectorSource(id, url) {
|
|
344
|
+
this.map.addSource(id, {
|
|
345
|
+
type: 'vector',
|
|
346
|
+
url,
|
|
347
|
+
});
|
|
348
|
+
}
|
|
349
|
+
/**
|
|
350
|
+
* Add a heatmap layer bound to an existing source. `maxzoom` controls the
|
|
351
|
+
* zoom at which the heatmap fades out in favour of individual-point layers.
|
|
352
|
+
*/
|
|
353
|
+
addHeatmapLayer(config) {
|
|
354
|
+
this.map.addLayer({
|
|
355
|
+
id: config.id,
|
|
356
|
+
type: 'heatmap',
|
|
357
|
+
source: config.source,
|
|
358
|
+
maxzoom: config.maxzoom,
|
|
359
|
+
paint: config.paint,
|
|
360
|
+
});
|
|
361
|
+
}
|
|
362
|
+
/**
|
|
363
|
+
* Apply a Mapbox filter expression to a layer, or pass `null` to clear it.
|
|
364
|
+
* Silently no-ops if the layer doesn't exist.
|
|
365
|
+
*/
|
|
366
|
+
setFilter(layerId, filter) {
|
|
367
|
+
if (this.map.getLayer(layerId)) {
|
|
368
|
+
this.map.setFilter(layerId, filter);
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
/**
|
|
372
|
+
* Change a paint property on any layer (color, opacity, width, etc.).
|
|
373
|
+
* Works on layers from the base style as well as layers you've added.
|
|
374
|
+
* Silently no-ops when the layer is missing so style swaps don't throw.
|
|
375
|
+
*
|
|
376
|
+
* @example
|
|
377
|
+
* map.setPaintProperty('road-primary', 'line-color', '#ff0080');
|
|
378
|
+
* map.setPaintProperty('water', 'fill-opacity', 0.6);
|
|
379
|
+
*/
|
|
380
|
+
setPaintProperty(layerId, name, value) {
|
|
381
|
+
if (this.map.getLayer(layerId)) {
|
|
382
|
+
this.map.setPaintProperty(layerId, name, value);
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
/**
|
|
386
|
+
* Change a layout property on any layer (visibility, icon-image, text-field, etc.).
|
|
387
|
+
*
|
|
388
|
+
* @example
|
|
389
|
+
* map.setLayoutProperty('poi-label', 'visibility', 'none');
|
|
390
|
+
* map.setLayoutProperty('road-label', 'text-size', 14);
|
|
391
|
+
*/
|
|
392
|
+
setLayoutProperty(layerId, name, value) {
|
|
393
|
+
if (this.map.getLayer(layerId)) {
|
|
394
|
+
this.map.setLayoutProperty(layerId, name, value);
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
/**
|
|
398
|
+
* Return every layer id currently in the style.
|
|
399
|
+
* Useful for discovering layer names from a custom Studio style so you can target them at runtime.
|
|
400
|
+
*/
|
|
401
|
+
getLayerIds() {
|
|
402
|
+
return this.map.getStyle().layers.map((l) => l.id);
|
|
403
|
+
}
|
|
404
|
+
/** `true` when a layer with this id exists in the current style. */
|
|
405
|
+
hasLayer(id) {
|
|
406
|
+
return !!this.map.getLayer(id);
|
|
407
|
+
}
|
|
408
|
+
/** `true` when a source with this id exists. */
|
|
409
|
+
hasSource(id) {
|
|
410
|
+
return !!this.map.getSource(id);
|
|
411
|
+
}
|
|
412
|
+
/** Remove a layer if present. Useful during style swaps or layer teardown. */
|
|
413
|
+
safeRemoveLayer(id) {
|
|
414
|
+
if (this.hasLayer(id)) {
|
|
415
|
+
this.map.removeLayer(id);
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
/** Convert geographic coordinates into pixel coordinates within the map container. */
|
|
419
|
+
project(lngLat) {
|
|
420
|
+
return this.map.project(lngLat);
|
|
421
|
+
}
|
|
422
|
+
/**
|
|
423
|
+
* Register an image for use with `icon-image` in symbol layers. Accepts
|
|
424
|
+
* either a pre-loaded `HTMLImageElement` or a URL to fetch. Updates an
|
|
425
|
+
* existing entry when the id is already registered.
|
|
426
|
+
*/
|
|
427
|
+
async addImage(id, img) {
|
|
428
|
+
const imgEl = typeof img === 'string' ? await this.loadImage(img) : img;
|
|
429
|
+
if (!this.map.hasImage(id)) {
|
|
430
|
+
this.map.addImage(id, imgEl, { sdf: false });
|
|
431
|
+
return;
|
|
432
|
+
}
|
|
433
|
+
this.map.updateImage(id, imgEl);
|
|
434
|
+
}
|
|
435
|
+
/** Flip a layer's `visibility` between `'visible'` and `'none'`. */
|
|
436
|
+
toggleLayerVisibility(layerId) {
|
|
437
|
+
const vis = this.map.getLayoutProperty(layerId, 'visibility');
|
|
438
|
+
this.map.setLayoutProperty(layerId, 'visibility', vis === 'visible' ? 'none' : 'visible');
|
|
439
|
+
}
|
|
440
|
+
/**
|
|
441
|
+
* Subscribe to a raw Mapbox event. Supports both the two-arg form
|
|
442
|
+
* (`on(event, handler)`) and the layer-scoped form (`on(event, layerId, handler)`).
|
|
443
|
+
*/
|
|
444
|
+
on(event, ...args) {
|
|
445
|
+
this.map.on(event, ...args);
|
|
446
|
+
}
|
|
447
|
+
/** Remove an event listener previously registered with `on`. */
|
|
448
|
+
off(event, ...args) {
|
|
449
|
+
this.map.off(event, ...args);
|
|
450
|
+
}
|
|
451
|
+
/** Remove a source from the style. Remove any layers using it first. */
|
|
452
|
+
removeSource(id) {
|
|
453
|
+
this.map.removeSource(id);
|
|
454
|
+
}
|
|
455
|
+
/** Set arbitrary feature-state for a feature in a GeoJSON source. */
|
|
456
|
+
setFeatureState(sourceId, featureId, state) {
|
|
457
|
+
if (!this.map.getSource(sourceId)) {
|
|
458
|
+
return;
|
|
459
|
+
}
|
|
460
|
+
this.map.setFeatureState({ source: sourceId, id: featureId }, state);
|
|
461
|
+
}
|
|
462
|
+
/** Remove a specific feature-state key, or all state for the feature when `key` is omitted. */
|
|
463
|
+
clearFeatureState(sourceId, featureId, key) {
|
|
464
|
+
if (!this.map.getSource(sourceId)) {
|
|
465
|
+
return;
|
|
466
|
+
}
|
|
467
|
+
if (!key) {
|
|
468
|
+
this.map.removeFeatureState({ source: sourceId, id: featureId });
|
|
469
|
+
return;
|
|
470
|
+
}
|
|
471
|
+
this.map.setFeatureState({ source: sourceId, id: featureId }, { [key]: false });
|
|
472
|
+
}
|
|
473
|
+
/**
|
|
474
|
+
* Enter polygon-drawing mode. Lazily mounts a `@mapbox/mapbox-gl-draw` control,
|
|
475
|
+
* hides its default UI (consumer controls the toggle), and switches to `draw_polygon`.
|
|
476
|
+
* The user clicks vertices and double-clicks (or clicks the first vertex) to close.
|
|
477
|
+
* The completed polygon is emitted on `polygonCreate`.
|
|
478
|
+
*/
|
|
479
|
+
enableDrawPolygon() {
|
|
480
|
+
if (!this.draw) {
|
|
481
|
+
this.draw = new MapboxDraw({
|
|
482
|
+
displayControlsDefault: false,
|
|
483
|
+
controls: {},
|
|
484
|
+
});
|
|
485
|
+
this.map.addControl(this.draw);
|
|
486
|
+
}
|
|
487
|
+
if (!this.onDrawCreate) {
|
|
488
|
+
this.onDrawCreate = (e) => {
|
|
489
|
+
const polygon = e.features.find((f) => f.geometry.type === 'Polygon');
|
|
490
|
+
if (polygon) {
|
|
491
|
+
this.polygonCreate.next(polygon);
|
|
492
|
+
}
|
|
493
|
+
};
|
|
494
|
+
this.map.on('draw.create', this.onDrawCreate);
|
|
495
|
+
}
|
|
496
|
+
this.lockInteractions();
|
|
497
|
+
this.draw.changeMode('draw_polygon');
|
|
498
|
+
}
|
|
499
|
+
/** Exit polygon-drawing mode and remove any in-progress or drawn polygons. */
|
|
500
|
+
disableDrawPolygon() {
|
|
501
|
+
if (this.onDrawCreate) {
|
|
502
|
+
this.map.off('draw.create', this.onDrawCreate);
|
|
503
|
+
this.onDrawCreate = undefined;
|
|
504
|
+
}
|
|
505
|
+
if (this.draw) {
|
|
506
|
+
this.draw.deleteAll();
|
|
507
|
+
this.map.removeControl(this.draw);
|
|
508
|
+
this.draw = undefined;
|
|
509
|
+
}
|
|
510
|
+
this.unlockInteractions();
|
|
511
|
+
}
|
|
512
|
+
/**
|
|
513
|
+
* Disable pan/zoom handlers so the viewport stays fixed while the user draws.
|
|
514
|
+
* Saves the prior enabled-state for each handler so it can be restored by
|
|
515
|
+
* `unlockInteractions`. Safe to call repeatedly — a second call is a no-op
|
|
516
|
+
* because saved state is only captured on the first lock.
|
|
517
|
+
*/
|
|
518
|
+
lockInteractions() {
|
|
519
|
+
if (this.savedInteractions) {
|
|
520
|
+
return;
|
|
521
|
+
}
|
|
522
|
+
this.savedInteractions = {
|
|
523
|
+
dragPan: this.map.dragPan.isEnabled(),
|
|
524
|
+
scrollZoom: this.map.scrollZoom.isEnabled(),
|
|
525
|
+
boxZoom: this.map.boxZoom.isEnabled(),
|
|
526
|
+
doubleClickZoom: this.map.doubleClickZoom.isEnabled(),
|
|
527
|
+
touchZoomRotate: this.map.touchZoomRotate.isEnabled(),
|
|
528
|
+
keyboard: this.map.keyboard.isEnabled(),
|
|
529
|
+
};
|
|
530
|
+
this.map.dragPan.disable();
|
|
531
|
+
this.map.scrollZoom.disable();
|
|
532
|
+
this.map.boxZoom.disable();
|
|
533
|
+
this.map.doubleClickZoom.disable();
|
|
534
|
+
this.map.touchZoomRotate.disable();
|
|
535
|
+
this.map.keyboard.disable();
|
|
536
|
+
}
|
|
537
|
+
/**
|
|
538
|
+
* Restore every pan/zoom handler to the enabled-state captured by
|
|
539
|
+
* `lockInteractions`. No-op when interactions were never locked.
|
|
540
|
+
*/
|
|
541
|
+
unlockInteractions() {
|
|
542
|
+
if (!this.savedInteractions) {
|
|
543
|
+
return;
|
|
544
|
+
}
|
|
545
|
+
const prev = this.savedInteractions;
|
|
546
|
+
if (prev.dragPan)
|
|
547
|
+
this.map.dragPan.enable();
|
|
548
|
+
if (prev.scrollZoom)
|
|
549
|
+
this.map.scrollZoom.enable();
|
|
550
|
+
if (prev.boxZoom)
|
|
551
|
+
this.map.boxZoom.enable();
|
|
552
|
+
if (prev.doubleClickZoom)
|
|
553
|
+
this.map.doubleClickZoom.enable();
|
|
554
|
+
if (prev.touchZoomRotate)
|
|
555
|
+
this.map.touchZoomRotate.enable();
|
|
556
|
+
if (prev.keyboard)
|
|
557
|
+
this.map.keyboard.enable();
|
|
558
|
+
this.savedInteractions = undefined;
|
|
559
|
+
}
|
|
560
|
+
/** Remove every polygon the user has drawn, keeping draw mode active. */
|
|
561
|
+
clearDrawnPolygons() {
|
|
562
|
+
this.draw?.deleteAll();
|
|
563
|
+
}
|
|
564
|
+
/** Fetch a URL into an `HTMLImageElement`. Resolves on `load`, rejects on `error`. */
|
|
565
|
+
loadImage(url) {
|
|
566
|
+
return new Promise((res, rej) => {
|
|
567
|
+
const img = new Image();
|
|
568
|
+
img.onload = () => res(img);
|
|
569
|
+
img.onerror = rej;
|
|
570
|
+
img.src = url;
|
|
571
|
+
});
|
|
572
|
+
}
|
|
573
|
+
static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.1", ngImport: i0, type: MapboxService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
|
|
574
|
+
static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.1", ngImport: i0, type: MapboxService, providedIn: 'root' }); }
|
|
575
|
+
}
|
|
576
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.1", ngImport: i0, type: MapboxService, decorators: [{
|
|
577
|
+
type: Injectable,
|
|
578
|
+
args: [{ providedIn: 'root' }]
|
|
579
|
+
}] });
|
|
580
|
+
|
|
581
|
+
/**
|
|
582
|
+
* Thin host component that mounts a Mapbox map into a container div, forwards
|
|
583
|
+
* lifecycle/events from `MapboxService`, and cleans up on destroy.
|
|
584
|
+
*
|
|
585
|
+
* Consumers interact with the underlying map via the public `map` (MapboxService)
|
|
586
|
+
* instance — use `viewChild(ApexMapComponent)` in a parent to reach `component.map`
|
|
587
|
+
* and call `addSource()`, `addLayer()`, `moveCenter()`, etc.
|
|
588
|
+
*
|
|
589
|
+
* Example:
|
|
590
|
+
* <apex-map [center]="[-80.84, 35.22]" [zoom]="11" (mapReady)="onReady()"/>
|
|
591
|
+
*/
|
|
592
|
+
class ApexMapComponent {
|
|
593
|
+
/**
|
|
594
|
+
* Wire a reactive effect that emits `mapReady` once the underlying Mapbox
|
|
595
|
+
* `load` event fires and `MapboxService.ready()` flips to `true`.
|
|
596
|
+
*/
|
|
597
|
+
constructor() {
|
|
598
|
+
this.center = input([-80.8431, 35.2271], ...(ngDevMode ? [{ debugName: "center" }] : []));
|
|
599
|
+
this.zoom = input(10, ...(ngDevMode ? [{ debugName: "zoom" }] : []));
|
|
600
|
+
this.mapStyle = input(undefined, ...(ngDevMode ? [{ debugName: "mapStyle" }] : []));
|
|
601
|
+
this.maxBounds = input(undefined, ...(ngDevMode ? [{ debugName: "maxBounds" }] : []));
|
|
602
|
+
this.showNavigation = input(true, ...(ngDevMode ? [{ debugName: "showNavigation" }] : []));
|
|
603
|
+
this.mapReady = output();
|
|
604
|
+
this.mapClick = output();
|
|
605
|
+
this.featureClick = output();
|
|
606
|
+
this.map = inject(MapboxService);
|
|
607
|
+
this.platformId = inject(PLATFORM_ID);
|
|
608
|
+
this.destroyRef = inject(DestroyRef);
|
|
609
|
+
this.container = viewChild.required('container');
|
|
610
|
+
effect(() => {
|
|
611
|
+
if (this.map.ready()) {
|
|
612
|
+
this.mapReady.emit();
|
|
613
|
+
}
|
|
614
|
+
});
|
|
615
|
+
}
|
|
616
|
+
/**
|
|
617
|
+
* Initialise the Mapbox instance into the `#container` div, forward
|
|
618
|
+
* `mapClick`/`featureClick` streams as component outputs, and register
|
|
619
|
+
* teardown so the map is destroyed with the component.
|
|
620
|
+
* No-op on non-browser platforms (SSR).
|
|
621
|
+
*/
|
|
622
|
+
ngAfterViewInit() {
|
|
623
|
+
if (!isPlatformBrowser(this.platformId)) {
|
|
624
|
+
return;
|
|
625
|
+
}
|
|
626
|
+
this.map.init({
|
|
627
|
+
container: this.container().nativeElement,
|
|
628
|
+
center: this.center(),
|
|
629
|
+
zoom: this.zoom(),
|
|
630
|
+
mapStyle: this.mapStyle(),
|
|
631
|
+
maxBounds: this.maxBounds(),
|
|
632
|
+
showNavigation: this.showNavigation(),
|
|
633
|
+
});
|
|
634
|
+
this.map.mapClick
|
|
635
|
+
.pipe(takeUntilDestroyed(this.destroyRef))
|
|
636
|
+
.subscribe((e) => this.mapClick.emit(e));
|
|
637
|
+
this.map.featureClick
|
|
638
|
+
.pipe(takeUntilDestroyed(this.destroyRef))
|
|
639
|
+
.subscribe((e) => this.featureClick.emit(e));
|
|
640
|
+
this.destroyRef.onDestroy(() => this.map.deactivate(this.container().nativeElement));
|
|
641
|
+
}
|
|
642
|
+
static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.1", ngImport: i0, type: ApexMapComponent, deps: [], target: i0.ɵɵFactoryTarget.Component }); }
|
|
643
|
+
static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.2.0", version: "21.2.1", type: ApexMapComponent, isStandalone: true, selector: "apex-map", inputs: { center: { classPropertyName: "center", publicName: "center", isSignal: true, isRequired: false, transformFunction: null }, zoom: { classPropertyName: "zoom", publicName: "zoom", isSignal: true, isRequired: false, transformFunction: null }, mapStyle: { classPropertyName: "mapStyle", publicName: "mapStyle", isSignal: true, isRequired: false, transformFunction: null }, maxBounds: { classPropertyName: "maxBounds", publicName: "maxBounds", isSignal: true, isRequired: false, transformFunction: null }, showNavigation: { classPropertyName: "showNavigation", publicName: "showNavigation", isSignal: true, isRequired: false, transformFunction: null } }, outputs: { mapReady: "mapReady", mapClick: "mapClick", featureClick: "featureClick" }, viewQueries: [{ propertyName: "container", first: true, predicate: ["container"], descendants: true, isSignal: true }], ngImport: i0, 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"], changeDetection: i0.ChangeDetectionStrategy.OnPush, encapsulation: i0.ViewEncapsulation.None }); }
|
|
644
|
+
}
|
|
645
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.1", ngImport: i0, type: ApexMapComponent, decorators: [{
|
|
646
|
+
type: Component,
|
|
647
|
+
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"] }]
|
|
648
|
+
}], 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 }] }] } });
|
|
649
|
+
|
|
650
|
+
/**
|
|
651
|
+
* Recursively flatten any nesting of GeoJSON coordinates down to a flat list of [lng, lat] pairs.
|
|
652
|
+
* Handles Point, LineString, Polygon, and MultiPolygon coordinate shapes uniformly.
|
|
653
|
+
*/
|
|
654
|
+
function flattenCoords(arr) {
|
|
655
|
+
const out = [];
|
|
656
|
+
const recurse = (node) => {
|
|
657
|
+
if (Array.isArray(node) &&
|
|
658
|
+
typeof node[0] === 'number' &&
|
|
659
|
+
typeof node[1] === 'number') {
|
|
660
|
+
out.push(node);
|
|
661
|
+
}
|
|
662
|
+
else if (Array.isArray(node)) {
|
|
663
|
+
node.forEach(recurse);
|
|
664
|
+
}
|
|
665
|
+
};
|
|
666
|
+
recurse(arr);
|
|
667
|
+
return out;
|
|
668
|
+
}
|
|
669
|
+
/**
|
|
670
|
+
* Compute the [[minLng, minLat], [maxLng, maxLat]] bounds of a flat list of coordinates.
|
|
671
|
+
* Return value is compatible with `mapboxgl.LngLatBoundsLike`.
|
|
672
|
+
*/
|
|
673
|
+
function calculateBounds(coords) {
|
|
674
|
+
let minX = 180;
|
|
675
|
+
let minY = 90;
|
|
676
|
+
let maxX = -180;
|
|
677
|
+
let maxY = -90;
|
|
678
|
+
coords.forEach(([lng, lat]) => {
|
|
679
|
+
if (lng < minX)
|
|
680
|
+
minX = lng;
|
|
681
|
+
if (lng > maxX)
|
|
682
|
+
maxX = lng;
|
|
683
|
+
if (lat < minY)
|
|
684
|
+
minY = lat;
|
|
685
|
+
if (lat > maxY)
|
|
686
|
+
maxY = lat;
|
|
687
|
+
});
|
|
688
|
+
return [
|
|
689
|
+
[minX, minY],
|
|
690
|
+
[maxX, maxY],
|
|
691
|
+
];
|
|
692
|
+
}
|
|
693
|
+
/**
|
|
694
|
+
* Build a closed square polygon of side `2 * radiusKm` centered at `center`.
|
|
695
|
+
* Useful when you need a small viewport-like polygon for point-in-polygon queries.
|
|
696
|
+
*/
|
|
697
|
+
function calculateViewportPolygonFromCenter(center, radiusKm = 0.5) {
|
|
698
|
+
const [lng, lat] = center;
|
|
699
|
+
const degreesPerMeterLng = 1 / (111320 * Math.cos((lat * Math.PI) / 180));
|
|
700
|
+
const degreesPerMeterLat = 1 / 110540;
|
|
701
|
+
const radiusMeters = radiusKm * 1000;
|
|
702
|
+
const lngDelta = radiusMeters * degreesPerMeterLng;
|
|
703
|
+
const latDelta = radiusMeters * degreesPerMeterLat;
|
|
704
|
+
return [
|
|
705
|
+
[
|
|
706
|
+
[lng - lngDelta, lat - latDelta],
|
|
707
|
+
[lng + lngDelta, lat - latDelta],
|
|
708
|
+
[lng + lngDelta, lat + latDelta],
|
|
709
|
+
[lng - lngDelta, lat + latDelta],
|
|
710
|
+
[lng - lngDelta, lat - latDelta],
|
|
711
|
+
],
|
|
712
|
+
];
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
/**
|
|
716
|
+
* Generated bundle index. Do not edit.
|
|
717
|
+
*/
|
|
718
|
+
|
|
719
|
+
export { ApexMapComponent, MAP_CONFIG, MapStyles, MapboxService, calculateBounds, calculateViewportPolygonFromCenter, flattenCoords, provideMap };
|
|
720
|
+
//# sourceMappingURL=apexara-map.mjs.map
|