@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 ADDED
@@ -0,0 +1,428 @@
1
+ # @apexara/map
2
+
3
+ A thin, opinionated Angular wrapper around [Mapbox GL JS](https://docs.mapbox.com/mapbox-gl-js/) for Apexara apps. Ships a ready-to-drop `<apex-map>` component and a `MapboxService` that exposes the underlying map through a small, typed surface with Angular signals for reactive state.
4
+
5
+ - **Angular**: 19+ (standalone components, signals, `inject()`, `input()`/`output()`)
6
+ - **Mapbox GL**: 3.x
7
+ - **SSR-safe**: every browser-only call no-ops on the server.
8
+
9
+ ---
10
+
11
+ ## Table of contents
12
+
13
+ - [Install](#install)
14
+ - [Configure](#configure)
15
+ - [Quick start](#quick-start)
16
+ - [The component: `<apex-map>`](#the-component-apex-map)
17
+ - [The service: `MapboxService`](#the-service-mapboxservice)
18
+ - [Reactive state (signals)](#reactive-state-signals)
19
+ - [Viewport & camera](#viewport--camera)
20
+ - [Sources](#sources)
21
+ - [Layers](#layers)
22
+ - [Filters, paint, layout](#filters-paint-layout)
23
+ - [Feature state](#feature-state)
24
+ - [Clusters](#clusters)
25
+ - [Events](#events)
26
+ - [Images & icons](#images--icons)
27
+ - [Teardown](#teardown)
28
+ - [Utilities](#utilities)
29
+ - [Types & tokens](#types--tokens)
30
+ - [Recipes](#recipes)
31
+ - [SSR notes](#ssr-notes)
32
+ - [Troubleshooting](#troubleshooting)
33
+
34
+ ---
35
+
36
+ ## Install
37
+
38
+ ```bash
39
+ npm install @apexara/map mapbox-gl
40
+ ```
41
+
42
+ Peer deps: `@angular/common >= 19`, `@angular/core >= 19`, `mapbox-gl ^3`, `rxjs ^7.8`.
43
+
44
+ You also need Mapbox's CSS once in your app (usually in `styles.css`):
45
+
46
+ ```css
47
+ @import 'mapbox-gl/dist/mapbox-gl.css';
48
+ ```
49
+
50
+ ---
51
+
52
+ ## Configure
53
+
54
+ Register the library at the application root with `provideMap`, passing your Mapbox public access token (`pk.*`).
55
+
56
+ ```ts
57
+ // app.config.ts
58
+ import { ApplicationConfig } from '@angular/core';
59
+ import { provideMap, MapStyles } from '@apexara/map';
60
+ import { environment } from './environments/environment';
61
+
62
+ export const appConfig: ApplicationConfig = {
63
+ providers: [
64
+ provideMap({
65
+ accessToken: environment.mapboxToken,
66
+ defaultStyle: MapStyles.LightV11, // optional
67
+ }),
68
+ ],
69
+ };
70
+ ```
71
+
72
+ `defaultStyle` is used whenever a consumer doesn't pass `mapStyle` to `<apex-map>`. It accepts a `MapStyles` enum value, a style URL, or a full inline `StyleSpecification`.
73
+
74
+ ---
75
+
76
+ ## Quick start
77
+
78
+ ```ts
79
+ // map-page.component.ts
80
+ import { Component, viewChild } from '@angular/core';
81
+ import { ApexMapComponent } from '@apexara/map';
82
+
83
+ @Component({
84
+ selector: 'app-map-page',
85
+ standalone: true,
86
+ imports: [ApexMapComponent],
87
+ template: `
88
+ <apex-map
89
+ [center]="[-80.8431, 35.2271]"
90
+ [zoom]="11"
91
+ (mapReady)="onReady()"
92
+ (mapClick)="onMapClick($event)"
93
+ style="display:block; width:100%; height:80vh;"
94
+ />
95
+ `,
96
+ })
97
+ export class MapPageComponent {
98
+ private readonly mapRef = viewChild.required(ApexMapComponent);
99
+
100
+ onReady(): void {
101
+ const map = this.mapRef().map;
102
+ map.addSource({
103
+ id: 'stops',
104
+ data: 'https://example.com/stops.geojson',
105
+ clustered: true,
106
+ clusterRadius: 40,
107
+ generateId: true,
108
+ });
109
+ map.addLayer({
110
+ id: 'stops-circles',
111
+ type: 'circle',
112
+ source: 'stops',
113
+ paint: { 'circle-radius': 5, 'circle-color': '#1f6feb' },
114
+ });
115
+ }
116
+
117
+ onMapClick(e: mapboxgl.MapMouseEvent): void {
118
+ console.log('clicked at', e.lngLat);
119
+ }
120
+ }
121
+ ```
122
+
123
+ > The host element of `<apex-map>` does not set its own width/height. Give it a size via your layout (flex/grid) or inline styles — an unsized container renders an invisible map.
124
+
125
+ ---
126
+
127
+ ## The component: `<apex-map>`
128
+
129
+ `ApexMapComponent` is a standalone component that mounts a `mapboxgl.Map` into an internal div and wires lifecycle/events through `MapboxService`.
130
+
131
+ ### Inputs
132
+
133
+ | Input | Type | Default | Notes |
134
+ | ---------------- | -------------------------------------------------- | ---------------------- | ------------------------------------------------------------------------------------------- |
135
+ | `center` | `[number, number]` (`[lng, lat]`) | `[-80.8431, 35.2271]` | Initial centre. |
136
+ | `zoom` | `number` | `10` | Initial zoom. |
137
+ | `mapStyle` | `string \| StyleSpecification \| undefined` | `undefined` | Falls back to `MapConfig.defaultStyle`, then `MapStyles.Streets`. |
138
+ | `maxBounds` | `mapboxgl.LngLatBoundsLike \| undefined` | world-ish `±175/±85` | Constrains panning. |
139
+ | `showNavigation` | `boolean` | `true` | Adds the built-in zoom control on `load`. |
140
+
141
+ ### Outputs
142
+
143
+ | Output | Payload | Fires when |
144
+ | -------------- | -------------------------- | ----------------------------------------------- |
145
+ | `mapReady` | `void` | Mapbox `load` has fired and the style is ready. |
146
+ | `mapClick` | `mapboxgl.MapMouseEvent` | User clicks empty canvas. |
147
+ | `featureClick` | `mapboxgl.MapMouseEvent` | A feature click is forwarded from the service. |
148
+
149
+ ### Accessing the service from a parent
150
+
151
+ ```ts
152
+ private readonly mapRef = viewChild.required(ApexMapComponent);
153
+
154
+ someAction() {
155
+ const map = this.mapRef().map; // MapboxService
156
+ map.moveCenter([-73.99, 40.73], 13);
157
+ }
158
+ ```
159
+
160
+ ---
161
+
162
+ ## The service: `MapboxService`
163
+
164
+ Provided at the root (`providedIn: 'root'`). Inject it directly when you don't want to go through the component:
165
+
166
+ ```ts
167
+ private readonly map = inject(MapboxService);
168
+ ```
169
+
170
+ All mutating methods assume `ready()` is `true`. Guard with an effect if you're unsure:
171
+
172
+ ```ts
173
+ constructor() {
174
+ effect(() => {
175
+ if (this.map.ready()) {
176
+ // safe to add sources/layers
177
+ }
178
+ });
179
+ }
180
+ ```
181
+
182
+ ### Reactive state (signals)
183
+
184
+ | Signal | Type | Notes |
185
+ | ---------- | ------------------------------------------------------------- | --------------------------------------------------- |
186
+ | `ready` | `Signal<boolean>` | `true` after the Mapbox `load` event. |
187
+ | `center` | `Signal<[number, number] \| null>` | Updates on `moveend`. |
188
+ | `zoom` | `Signal<number \| null>` | Updates on `moveend`. |
189
+ | `bounds` | `Signal<[[number, number], [number, number]] \| null>` | `[[swLng, swLat], [neLng, neLat]]`. On `moveend`. |
190
+ | `isMoving` | `Signal<boolean>` | `true` between `movestart` and `moveend`. |
191
+
192
+ ### Viewport & camera
193
+
194
+ - `init(options)` — create the underlying map. Called automatically by `<apex-map>`; call yourself only if you're managing your own container.
195
+ - `getCenter()` / `getZoom()` — imperative reads; prefer the signals.
196
+ - `getViewportPolygon()` — the current viewport as a closed GeoJSON ring (`[sw, se, ne, nw, sw]`).
197
+ - `moveCenter([lng, lat], zoom = 13)` — animated `flyTo`.
198
+ - `fitBounds(bounds, padding = 40)` — animated `fitBounds`.
199
+ - `project(lngLat)` — geographic → pixel coordinates.
200
+ - `setStyle(styleUrl)` — swap the base style. **Re-apply your custom sources/layers after `styledata` — Mapbox drops them during the swap.**
201
+
202
+ ### Sources
203
+
204
+ ```ts
205
+ map.addSource({
206
+ id: 'stops',
207
+ data: geojson, // FeatureCollection or URL string
208
+ clustered: true,
209
+ clusterRadius: 40,
210
+ clusterMaxZoom: 14,
211
+ generateId: true, // required if you'll use feature-state
212
+ });
213
+
214
+ map.updateSource('stops', nextFeatureCollection);
215
+ map.addVectorSource('transit', 'mapbox://apexara.transit-v1');
216
+ map.removeSource('stops');
217
+ map.hasSource('stops'); // boolean
218
+ ```
219
+
220
+ ### Layers
221
+
222
+ ```ts
223
+ map.addLayer({
224
+ id: 'stops-circles',
225
+ type: 'circle',
226
+ source: 'stops',
227
+ paint: { 'circle-radius': 5, 'circle-color': '#1f6feb' },
228
+ }, 'road-label'); // optional beforeId
229
+
230
+ map.addRasterLayer('tiles', 'https://...'); // starts hidden
231
+ map.addHeatmapLayer({
232
+ id: 'heat',
233
+ source: 'stops',
234
+ maxzoom: 14,
235
+ paint: { 'heatmap-radius': 20, 'heatmap-opacity': 0.7 },
236
+ });
237
+
238
+ map.toggleLayerVisibility('tiles');
239
+ map.getLayerIds(); // all layer ids in the current style
240
+ map.hasLayer('stops-circles');
241
+ map.safeRemoveLayer('stops-circles');
242
+ ```
243
+
244
+ ### Filters, paint, layout
245
+
246
+ ```ts
247
+ map.setFilter('stops-circles', ['==', ['get', 'type'], 'metro']);
248
+ map.setFilter('stops-circles', null); // clear
249
+
250
+ map.setPaintProperty('stops-circles', 'circle-color', '#ff0080');
251
+ map.setLayoutProperty('poi-label', 'visibility', 'none');
252
+ ```
253
+
254
+ All three silently no-op when the layer is missing, so they're safe to call during style swaps.
255
+
256
+ ### Feature state
257
+
258
+ Feature state powers hover/selected styling without re-uploading data. Requires a source with `generateId: true` (or features with stable numeric ids).
259
+
260
+ ```ts
261
+ map.setFeatureState('stops', 42, { hovered: true });
262
+ map.clearFeatureState('stops', 42, 'hovered'); // clear one key
263
+ map.clearFeatureState('stops', 42); // clear all state
264
+ ```
265
+
266
+ Reference it in paint expressions:
267
+
268
+ ```ts
269
+ 'circle-color': [
270
+ 'case',
271
+ ['boolean', ['feature-state', 'hovered'], false], '#ff0080',
272
+ '#1f6feb',
273
+ ]
274
+ ```
275
+
276
+ ### Clusters
277
+
278
+ ```ts
279
+ // Expand a cluster on click
280
+ map.on('click', 'clusters', async (e: mapboxgl.MapMouseEvent) => {
281
+ const props = map.getFeatureProperties<{ cluster_id: number }>(e);
282
+ if (!props) return;
283
+ const leaves = await map.getClusterProperties('stops', props.cluster_id);
284
+ console.log(leaves);
285
+ });
286
+ ```
287
+
288
+ `getClusterProperties(sourceId, clusterId, limit = 10000, offset = 0)` rejects if the source is missing or not clustered.
289
+
290
+ ### Events
291
+
292
+ `on` supports both the raw two-arg form and the layer-scoped three-arg form:
293
+
294
+ ```ts
295
+ map.on('click', 'stops-circles', (e) => { /* feature click */ });
296
+ map.on('mouseenter', 'stops-circles', () => { /* ... */ });
297
+ map.off('click', 'stops-circles', handler);
298
+ ```
299
+
300
+ `getRenderedFeatures(point, { layers })` queries what's drawn under a screen point.
301
+
302
+ `getFeatureProperties<T>(event)` is a convenience to pull typed `properties` off the first feature in an event.
303
+
304
+ ### Images & icons
305
+
306
+ ```ts
307
+ await map.addImage('stop-pin', '/assets/stop-pin.png'); // URL or HTMLImageElement
308
+ // then reference in a symbol layer: { 'icon-image': 'stop-pin' }
309
+ ```
310
+
311
+ Re-calling with an existing id updates the image in place.
312
+
313
+ ### Teardown
314
+
315
+ `destroy()` removes the map and resets every signal. The component calls it automatically via `DestroyRef`, so you only need this if you called `init()` yourself.
316
+
317
+ ---
318
+
319
+ ## Utilities
320
+
321
+ Pure helpers exported from the package:
322
+
323
+ ```ts
324
+ import {
325
+ flattenCoords,
326
+ calculateBounds,
327
+ calculateViewportPolygonFromCenter,
328
+ } from '@apexara/map';
329
+
330
+ const coords = flattenCoords(polygon.coordinates);
331
+ const bounds = calculateBounds(coords);
332
+ map.fitBounds(bounds, 60);
333
+
334
+ const ring = calculateViewportPolygonFromCenter([-80.84, 35.22], 0.5);
335
+ ```
336
+
337
+ - `flattenCoords(arr)` — flatten any GeoJSON coordinate nesting into `[lng, lat][]`.
338
+ - `calculateBounds(coords)` — `[[minLng, minLat], [maxLng, maxLat]]`, compatible with `LngLatBoundsLike`.
339
+ - `calculateViewportPolygonFromCenter(center, radiusKm = 0.5)` — a closed square ring around `center`.
340
+
341
+ ---
342
+
343
+ ## Types & tokens
344
+
345
+ ```ts
346
+ import {
347
+ provideMap,
348
+ MAP_CONFIG,
349
+ type MapConfig,
350
+ MapStyles,
351
+ type MapInitOptions,
352
+ type SourceConfig,
353
+ } from '@apexara/map';
354
+ ```
355
+
356
+ - `MapStyles` — enum of common Mapbox-hosted styles (`Streets`, `Sat`, `DarkV11`, `LightV11`, `OutdoorsV12`).
357
+ - `MapInitOptions` — shape accepted by `MapboxService.init` (the component builds this for you).
358
+ - `SourceConfig` — shape accepted by `addSource` (GeoJSON + clustering flags).
359
+ - `MapConfig` / `MAP_CONFIG` — root-level token, usually set via `provideMap`.
360
+
361
+ ---
362
+
363
+ ## Recipes
364
+
365
+ ### Hover highlight via feature-state
366
+
367
+ ```ts
368
+ let hoveredId: number | null = null;
369
+
370
+ map.on('mousemove', 'stops-circles', (e: mapboxgl.MapMouseEvent) => {
371
+ const id = e.features?.[0]?.id as number | undefined;
372
+ if (id === undefined) return;
373
+ if (hoveredId !== null) map.clearFeatureState('stops', hoveredId, 'hovered');
374
+ hoveredId = id;
375
+ map.setFeatureState('stops', id, { hovered: true });
376
+ });
377
+
378
+ map.on('mouseleave', 'stops-circles', () => {
379
+ if (hoveredId !== null) map.clearFeatureState('stops', hoveredId, 'hovered');
380
+ hoveredId = null;
381
+ });
382
+ ```
383
+
384
+ ### Reacting to viewport changes
385
+
386
+ ```ts
387
+ constructor() {
388
+ effect(() => {
389
+ const b = this.map.bounds();
390
+ if (!b) return;
391
+ this.loadForBounds(b); // e.g. refetch markers within the visible area
392
+ });
393
+ }
394
+ ```
395
+
396
+ ### Swapping styles safely
397
+
398
+ ```ts
399
+ map.on('styledata', () => {
400
+ // Re-add your custom sources/layers here — Mapbox wiped them.
401
+ if (!map.hasSource('stops')) map.addSource({ id: 'stops', data: /* ... */ });
402
+ if (!map.hasLayer('stops-circles')) map.addLayer({ /* ... */ });
403
+ });
404
+ map.setStyle(MapStyles.DarkV11);
405
+ ```
406
+
407
+ ---
408
+
409
+ ## SSR notes
410
+
411
+ - `MapboxService.init` is a no-op on the server, and `<apex-map>` guards its `ngAfterViewInit` with `isPlatformBrowser`, so the component renders an empty container during SSR without throwing.
412
+ - Avoid calling mutating methods (`addSource`, `addLayer`, etc.) during SSR — gate them on `map.ready()`.
413
+
414
+ ---
415
+
416
+ ## Troubleshooting
417
+
418
+ - **Blank map** — the container has no height. Give `<apex-map>` an explicit size.
419
+ - **`401 Unauthorized` tiles** — the access token passed to `provideMap` is wrong or not a public (`pk.*`) token.
420
+ - **Sources/layers disappear after `setStyle`** — Mapbox replaces the entire style. Re-add them in a `styledata` listener.
421
+ - **`setFeatureState` does nothing** — the source was added without `generateId: true` and features have no numeric `id`.
422
+ - **Cluster expand rejects** — the `sourceId` either doesn't exist or was added without `clustered: true`.
423
+
424
+ ---
425
+
426
+ ## License
427
+
428
+ ISC © Apexara