-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathleaflet-live-map.js
More file actions
636 lines (561 loc) · 23.2 KB
/
leaflet-live-map.js
File metadata and controls
636 lines (561 loc) · 23.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { inject as service } from '@ember/service';
import { action, set } from '@ember/object';
import { isArray } from '@ember/array';
import { debug } from '@ember/debug';
import { guidFor } from '@ember/object/internals';
import { camelize, capitalize, dasherize } from '@ember/string';
import { singularize, pluralize } from 'ember-inflector';
import { all } from 'rsvp';
import { task } from 'ember-concurrency';
import getModelName from '@fleetbase/ember-core/utils/get-model-name';
export default class MapLeafletLiveMapComponent extends Component {
@service leafletMapManager;
@service leafletLayerVisibilityManager;
@service leafletContextmenuManager;
@service resourceContextPanel;
@service serviceAreaActions;
@service zoneActions;
@service placeActions;
@service vehicleActions;
@service driverActions;
@service movementTracker;
@service geofence;
@service location;
@service fetch;
@service abilities;
@service intl;
@service universe;
@service('universe/menu-service') menuService;
@service geofenceEventBus;
/** properties */
id = guidFor(this);
/** tracked properties */
@tracked ready = false;
@tracked zoom = this.getValidZoom();
@tracked latitude = this.location.getLatitude();
@tracked longitude = this.location.getLongitude();
@tracked contextmenuItems = [];
@tracked tileUrl = 'https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png';
@tracked theme = 'light';
@tracked routes = [];
@tracked drivers = [];
@tracked vehicles = [];
@tracked places = [];
constructor() {
super(...arguments);
// Store bound function reference for proper cleanup
this._locationUpdateHandler = this.#handleLocationUpdate.bind(this);
// Listen for location updates from the location service
this.universe.on('user.located', this._locationUpdateHandler);
// Ensure we have valid coordinates on initialization
this.#updateCoordinatesFromLocation();
// Subscribe to geofence events so the live map can react to boundary crossings
this._geofenceEnteredHandler = this.#handleGeofenceEntered.bind(this);
this._geofenceExitedHandler = this.#handleGeofenceExited.bind(this);
this.universe.on('fleet-ops.geofence.entered', this._geofenceEnteredHandler);
this.universe.on('fleet-ops.geofence.exited', this._geofenceExitedHandler);
}
willDestroy() {
super.willDestroy();
// Clean up event listener using stored reference
if (this._locationUpdateHandler) {
this.universe.off('user.located', this._locationUpdateHandler);
this._locationUpdateHandler = null;
}
if (this._geofenceEnteredHandler) {
this.universe.off('fleet-ops.geofence.entered', this._geofenceEnteredHandler);
this._geofenceEnteredHandler = null;
}
if (this._geofenceExitedHandler) {
this.universe.off('fleet-ops.geofence.exited', this._geofenceExitedHandler);
this._geofenceExitedHandler = null;
}
}
@action didLoad({ target: map }) {
this.#setMap(map);
this.#createMapContextMenu(map);
this.trigger('onLoad', ...arguments);
this.load.perform();
// Listen for map move/zoom events to trigger viewport-based resource reload
map.on('moveend', () => this.reloadResourcesInViewport.perform());
map.on('zoomend', () => this.reloadResourcesInViewport.perform());
}
@action trigger(name, ...rest) {
if (typeof this[name] === 'function') {
this[name](...rest);
}
if (typeof this.args[name] === 'function') {
this.args[name](...rest);
}
// Fire as universe event
const uevent = dasherize(name);
this.universe.trigger(`fleet-ops.live-map.${uevent}`, ...rest);
}
@action didCreateDrawControl(drawControl) {
this.leafletMapManager.setDrawControl(drawControl);
this.trigger('onDrawControlCreated', ...arguments);
}
@action didCreateDrawControlFeatureGroup(featureGroup) {
this.leafletMapManager.setDrawControlFeatureGroup(featureGroup);
this.trigger('onDrawFeatureGroupCreated', ...arguments);
}
@action onDriverAdded(driver, { target: layer }) {
this.#setResourceLayer(driver, layer);
this.#createDriverContextMenu(driver, layer);
this.movementTracker.track(driver);
}
@action onDriverClicked(driver) {
this.driverActions.panel.view(driver, {
size: 'xs',
onOpen: () => {
this.map.once('moveend', () => {
this.map.panBy([200, 0]);
});
},
});
}
@action onVehicleAdded(vehicle, { target: layer }) {
this.#setResourceLayer(vehicle, layer);
this.#createVehicleContextMenu(vehicle, layer);
this.movementTracker.track(vehicle);
}
@action onVehicleClicked(vehicle) {
this.vehicleActions.panel.view(vehicle, {
size: 'xs',
onOpen: () => {
this.map.once('moveend', () => {
this.map.panBy([200, 0]);
});
},
});
}
@action onPlaceAdded(place, { target: layer }) {
this.#setResourceLayer(place, layer);
}
@action onPlaceClicked(place) {
this.placeActions.panel.view(place, {
size: 'xs',
onOpen: () => {
this.map.once('moveend', () => {
this.map.panBy([200, 0]);
});
},
});
}
@action onServiceAreaLayerAdded(serviceArea, { target: layer }) {
this.#setResourceLayer(serviceArea, layer, { hidden: true });
this.#createServiceAreaContextMenu(serviceArea, layer);
}
@action onZoneLayerAdd(zone, { target: layer }) {
this.#setResourceLayer(zone, layer, { hidden: true });
this.#createZoneContextMenu(zone, layer);
}
/** load resources and wait for stuff here and trigger map ready **/
@task *load() {
try {
// Get initial map bounds for spatial filtering
const bounds = this.map ? this.map.getBounds() : null;
const params = bounds
? {
bounds: [bounds.getSouth(), bounds.getWest(), bounds.getNorth(), bounds.getEast()],
}
: {};
const data = yield all([
this.loadResource.perform('routes'),
this.loadResource.perform('vehicles', { params }),
this.loadResource.perform('drivers', { params }),
this.loadResource.perform('places', { params }),
this.loadResource.perform('service-areas'),
]);
this.#createMapContextMenu(this.map);
this.trigger('onLoaded', { map: this.map, data });
this.ready = true;
} catch (err) {
debug('Failed to load live map: ' + err.message);
}
}
@task({ restartable: true }) *reloadResourcesInViewport() {
if (!this.map) {
return;
}
// Get current map bounds
const bounds = this.map.getBounds();
const params = {
bounds: [bounds.getSouth(), bounds.getWest(), bounds.getNorth(), bounds.getEast()],
};
// Reload spatially-filtered resources (drivers, vehicles, places)
// Orders, routes, and service-areas are not spatially filtered
try {
yield all([this.loadResource.perform('vehicles', { params }), this.loadResource.perform('drivers', { params }), this.loadResource.perform('places', { params })]);
} catch (err) {
debug('Failed to reload resources in viewport: ' + err.message);
}
}
@task *loadResource(path, options = {}) {
if (this.abilities.cannot(`fleet-ops list ${path}`)) return [];
if (path === 'service-areas') {
const serviceAreas = yield this.serviceAreaActions.loadAll.perform();
this.trigger('onServiceAreasLoaded', serviceAreas);
return serviceAreas;
}
const name = camelize(path);
const callback = `on${capitalize(name)}Loaded`;
const params = options.params ?? {};
const url = `fleet-ops/live/${path}`;
try {
const data = yield this.fetch.get(url, params, { normalizeToEmberData: true, normalizeModelType: singularize(dasherize(name)) });
this.trigger(callback, data);
this[name] = data;
if (typeof options.onLoaded === 'function') {
options.onLoaded(data);
}
return data;
} catch (err) {
debug('Failed to load resource: ' + err.message);
if (typeof options.onFailure === 'function') {
options.onFailure(err);
}
}
}
isReady() {
return this.ready === true;
}
/**
* Get valid zoom level for map initialization
* @returns {number} Valid zoom level between 1-20
*/
getValidZoom() {
const zoom = this.args.zoom;
// Validate zoom is a valid number within Leaflet bounds (1-20)
if (typeof zoom === 'number' && !isNaN(zoom) && zoom >= 1 && zoom <= 20) {
return zoom;
}
// Return default zoom of 14 if invalid
return 14;
}
/**
* Handles a geofence.entered event from the GeofenceEventBus.
* Briefly highlights the geofence layer on the map to provide visual feedback.
*
* @param {Object} event - Normalised geofence event object
*/
#handleGeofenceEntered(event) {
debug(`[LiveMap] geofence.entered — driver: ${event.driverName}, geofence: ${event.geofenceName}`);
this.#flashGeofenceLayer(event.geofenceUuid, '#22c55e'); // green
}
/**
* Handles a geofence.exited event from the GeofenceEventBus.
* Briefly highlights the geofence layer on the map to provide visual feedback.
*
* @param {Object} event - Normalised geofence event object
*/
#handleGeofenceExited(event) {
debug(`[LiveMap] geofence.exited — driver: ${event.driverName}, geofence: ${event.geofenceName}`);
this.#flashGeofenceLayer(event.geofenceUuid, '#ef4444'); // red
}
/**
* Briefly changes the fill colour of a geofence polygon layer on the map
* to provide visual feedback when a driver enters or exits.
*
* @param {string} geofenceUuid - UUID of the zone or service area
* @param {string} flashColor - Hex colour to flash
*/
#flashGeofenceLayer(geofenceUuid, flashColor) {
if (!geofenceUuid || !this.map) {
return;
}
// Iterate over all Leaflet layers to find the matching geofence polygon
this.map.eachLayer((layer) => {
const model = layer._model;
if (model && model.uuid === geofenceUuid && typeof layer.setStyle === 'function') {
const originalStyle = {
color: layer.options.color,
fillColor: layer.options.fillColor,
weight: layer.options.weight,
};
// Flash to the event colour
layer.setStyle({ color: flashColor, fillColor: flashColor, weight: 3 });
// Restore original style after 2 seconds
setTimeout(() => {
if (!layer._map) return; // layer may have been removed
layer.setStyle(originalStyle);
}, 2000);
}
});
}
/**
* Handles location updates from the location service
* @param {Object} coordinates - The new coordinates
*/
#handleLocationUpdate(coordinates) {
if (coordinates && typeof coordinates.latitude === 'number' && typeof coordinates.longitude === 'number') {
this.latitude = coordinates.latitude;
this.longitude = coordinates.longitude;
// Update map position if map is loaded
if (this.map && this.map.setView) {
this.map.setView([coordinates.latitude, coordinates.longitude], this.zoom);
}
}
}
/**
* Updates coordinates from location service on initialization
*/
#updateCoordinatesFromLocation() {
// Initial coordinates are already set via tracked properties
// This method ensures we have the latest location service values
this.latitude = this.location.getLatitude();
this.longitude = this.location.getLongitude();
}
#setMap(map) {
set(map, 'livemap', this);
this.map = map;
this.leafletMapManager.setMap(map);
this.universe.trigger('fleet-ops.live-map.loaded', map);
this.universe.set('component:fleet-ops:live-map', this);
}
#setResourceLayer(model, layer, options = {}) {
const { hidden = false } = options;
const type = getModelName(model);
set(model, 'leafletLayer', layer);
set(layer, 'record_id', model.id);
set(layer, 'record_type', type);
this.leafletLayerVisibilityManager.registerLayer(pluralize(type), layer, { id: model.id, hidden });
}
#createMapContextMenu(map) {
const items = [
{
text: this.intl.t('live-map.show-coordinates'),
callback: this.leafletMapManager.showCoordinates,
index: 0,
},
{
text: this.intl.t('live-map.center-map'),
callback: this.leafletMapManager.centerMap,
index: 1,
},
{
text: this.intl.t('live-map.zoom-in'),
callback: this.leafletMapManager.zoomIn,
index: 2,
},
{
text: this.intl.t('live-map.zoom-out'),
callback: this.leafletMapManager.zoomOut,
index: 3,
},
{
text: this.intl.t('live-map.toggle-draw-controls'),
callback: this.leafletMapManager.toggleDrawControl,
index: 4,
},
{ separator: true },
{
text: this.intl.t('live-map.create-new-service'),
callback: () => this.geofence.createServiceArea(),
index: 5,
},
this.serviceAreaActions.serviceAreas.length ? { separator: true } : null,
...this.serviceAreaActions.serviceAreas.map((serviceArea, i) => {
return {
text: this.intl.t('live-map.focus-service', { serviceName: serviceArea.name }),
callback: () => this.geofence.focusServiceArea(serviceArea),
index: 6 + i,
};
}),
].filter(Boolean);
const registry = this.leafletContextmenuManager.createContextMenu('map', map, items);
this.universe.trigger('fleet-ops:contextmenu:map:created', registry, this.leafletContextmenuManager);
return registry;
}
#createZoneContextMenu(zone, layer) {
let items = [
{
separator: true,
},
{
text: this.intl.t('live-map.edit-zone', { zoneName: zone.name }),
callback: () => this.zoneActions.modal.edit(zone),
},
{
text: this.intl.t('live-map.edit-boundaries', { resource: zone.name }),
callback: () => this.geofence.editZone(zone),
},
{
text: this.intl.t('live-map.delete-zone', { zoneName: zone.name }),
callback: () => this.zoneActions.delete(zone),
},
];
// create contextmenu registry
const contextmenuRegistry = this.leafletContextmenuManager.createContextMenu(`zone:${zone.public_id}`, layer, items, { zone });
this.universe.trigger('fleet-ops:contextmenu:zone:created', contextmenuRegistry, this.leafletContextmenuManager);
return contextmenuRegistry;
}
#createServiceAreaContextMenu(serviceArea, layer) {
let items = [
{
separator: true,
},
{
text: this.intl.t('live-map.blur-service', { serviceName: serviceArea.name }),
callback: () => this.geofence.blurServiceArea(serviceArea),
},
{
text: this.intl.t('live-map.create-zone', { serviceName: serviceArea.name }),
callback: () => this.geofence.createZone(serviceArea),
},
{
text: this.intl.t('live-map.edit-service', { serviceName: serviceArea.name }),
callback: () => this.serviceAreaActions.modal.edit(serviceArea),
},
{
text: this.intl.t('live-map.edit-boundaries', { resource: serviceArea.name }),
callback: () => this.geofence.editServiceArea(serviceArea),
},
{
text: this.intl.t('live-map.delete-service', { serviceName: serviceArea.name }),
callback: () => this.serviceAreaActions.delete(serviceArea),
},
];
// create contextmenu registry
const contextmenuRegistry = this.leafletContextmenuManager.createContextMenu(`service-area:${serviceArea.public_id}`, layer, items, { serviceArea });
this.universe.trigger('fleet-ops:contextmenu:service-area:created', contextmenuRegistry, this.leafletContextmenuManager);
return contextmenuRegistry;
}
#createDriverContextMenu(driver, layer) {
let items = [
{
separator: true,
},
{
text: this.intl.t('live-map.view-driver', { driverName: driver.name }),
callback: () => this.driverActions.panel.view(driver),
},
{
text: this.intl.t('live-map.edit-driver', { driverName: driver.name }),
callback: () => this.driverActions.panel.edit(driver, { useDefaultSaveTask: true }),
},
{
text: this.intl.t('live-map.delete-driver', { driverName: driver.name }),
callback: () => this.driverActions.delete(driver),
},
{
text: this.intl.t('live-map.view-vehicle-for', { driverName: driver.name }),
callback: () => this.vehicleActions.panel.view(driver.vehicle),
},
];
// append items from universe registry
const registeredContextMenuItems = this.menuService.getMenuItems('fleet-ops:contextmenu:driver');
if (isArray(registeredContextMenuItems)) {
items = [
...items,
...registeredContextMenuItems.map((menuItem) => {
return {
text: menuItem.title,
callback: () => {
const callbackContext = {
driver,
layer,
contextmenuService: this.leafletContextmenuManager,
menuItem,
};
return menuItem.onClick(callbackContext);
},
};
}),
];
}
// create contextmenu registry
const contextmenuRegistry = this.leafletContextmenuManager.createContextMenu(`driver:${driver.public_id}`, layer, items, { driver });
this.universe.trigger('fleet-ops:contextmenu:driver:created', contextmenuRegistry, this.leafletContextmenuManager);
return contextmenuRegistry;
}
#createVehicleContextMenu(vehicle, layer) {
let items = [
{
separator: true,
},
{
text: this.intl.t('live-map.view-vehicle', { vehicleName: vehicle.displayName }),
callback: () => this.vehicleActions.panel.view(vehicle),
},
{
text: this.intl.t('live-map.edit-vehicle', { vehicleName: vehicle.displayName }),
callback: () => this.vehicleActions.panel.edit(vehicle, { useDefaultSaveTask: true }),
},
{
text: this.intl.t('live-map.delete-vehicle', { vehicleName: vehicle.displayName }),
callback: () => this.vehicleActions.delete(vehicle),
},
];
// append items from universe registry
const registeredContextMenuItems = this.menuService.getMenuItems('fleet-ops:contextmenu:vehicle');
if (isArray(registeredContextMenuItems)) {
items = [
...items,
...registeredContextMenuItems.map((menuItem) => {
return {
text: menuItem.title,
callback: () => {
const callbackContext = {
vehicle,
layer,
contextmenuService: this.leafletContextmenuManager,
menuItem,
};
return menuItem.onClick(callbackContext);
},
};
}),
];
}
// create contextmenu registry
const contextmenuRegistry = this.leafletContextmenuManager.createContextMenu(`vehicle:${vehicle.public_id}`, layer, items, { vehicle });
this.universe.trigger('fleet-ops:contextmenu:vehicle:created', contextmenuRegistry, this.leafletContextmenuManager);
return contextmenuRegistry;
}
/**
* Safely gets a valid latitude value with fallback to default
* @returns {number} Valid latitude value
*/
#getValidLatitude() {
const lat = this.location.getLatitude();
// Validate latitude is a number and within valid range (-90 to 90)
if (typeof lat === 'number' && !isNaN(lat) && lat >= -90 && lat <= 90) {
return lat;
}
// Fallback to default Singapore latitude
return 1.369;
}
/**
* Safely gets a valid longitude value with fallback to default
* @returns {number} Valid longitude value
*/
#getValidLongitude() {
const lng = this.location.getLongitude();
// Validate longitude is a number and within valid range (-180 to 180)
if (typeof lng === 'number' && !isNaN(lng) && lng >= -180 && lng <= 180) {
return lng;
}
// Fallback to default Singapore longitude
return 103.8864;
}
#changeTileSource(source) {
switch (source) {
case 'dark':
this.theme = 'dark';
this.tileUrl = 'https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png';
break;
case 'custom':
this.theme = 'custom';
this.tileUrl = source.startsWith('https://') ? source : 'https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png';
break;
case 'light':
default:
this.theme = 'light';
this.tileUrl = 'https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png';
break;
}
}
}