forked from SignalK/freeboard-sk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfb-map.component.ts
More file actions
2186 lines (2051 loc) · 65.4 KB
/
Copy pathfb-map.component.ts
File metadata and controls
2186 lines (2051 loc) · 65.4 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
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
Component,
OnInit,
OnDestroy,
Input,
Output,
EventEmitter,
ViewChild,
SimpleChanges,
signal,
computed,
input,
effect,
inject,
NgZone
} from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatListModule } from '@angular/material/list';
import { MatIconModule } from '@angular/material/icon';
import { MatTooltipModule } from '@angular/material/tooltip';
import { MatMenuModule, MatMenuTrigger } from '@angular/material/menu';
import { MatBottomSheet } from '@angular/material/bottom-sheet';
// ** OL & popvers **
import {
PopoverComponent,
FeatureListPopoverComponent,
ChartListPopoverComponent,
AtoNPopoverComponent,
AircraftPopoverComponent,
AlarmPopoverComponent,
ResourcePopoverComponent,
ResourceSetPopoverComponent,
VesselPopoverComponent,
S57PopoverComponent,
S57_CLICKABLE_LAYERS,
S57_NAMES
} from './popovers';
import { FreeboardOpenlayersModule } from 'src/app/modules/map/ol';
import { CoordsPipe } from 'src/app/lib/pipes';
import { computeDestinationPoint, getGreatCircleBearing } from 'geolib';
import { toLonLat } from 'ol/proj';
import { Style, Stroke, Fill } from 'ol/style';
import { Collection, Feature } from 'ol';
import { Feature as GeoJsonFeature } from 'geojson';
import { Convert, TARGET_UNIT } from 'src/app/lib/convert';
import { GeoUtils, Angle } from 'src/app/lib/geoutils';
import { computeCursorEta, CursorEtaInfo } from './cursor-eta';
import {
FBRoute,
FBRoutes,
LineString,
MultiLineString,
Position
} from 'src/app/types';
import { AppFacade } from 'src/app/app.facade';
import { PlotterExtensionService } from 'src/app/modules/plotterext/plotterext.service';
import {
SKResourceService,
FBCustomResourceService,
SKChart,
SKWaypoint,
SKVessel,
SKAtoN,
SKAircraft,
SKSaR,
SKMeteo,
SKStreamFacade,
AnchorService,
NotificationManager,
CourseService,
SettingsFacade,
WeatherForecastModal,
InfoPanelFacade,
SKResourceType
} from 'src/app/modules';
import {
mapControls,
aircraftStyles,
sarStyles,
regionStyles,
routeStyles,
anchorStyles,
alarmStyles,
destinationStyles,
laylineStyles,
drawStyles,
routeDraftStyles,
targetAngleStyle,
raceCourseStyles,
bearingDistanceStyle
} from './mapconfig';
import { SKRoute } from 'src/app/modules/skresources/resource-classes';
import {
RouteBuffer,
RouteBufferRegistry
} from 'src/app/modules/plotterext/route-buffer.registry';
import { ModifyEvent } from 'ol/interaction/Modify';
import { DrawEvent } from 'ol/interaction/Draw';
import { Coordinate } from 'ol/coordinate';
import { SKPosition } from 'src/app/types';
import {
FBMapEvent,
FBPointerEvent,
zoomOffsetLevel,
MapComponent
} from './ol/lib/map.component';
import { FeatureLike } from 'ol/Feature';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import {
FBMapInteractService,
DrawFeatureInfo,
IPopover
} from './fbmap-interact.service';
import { ScaleLine } from 'ol/control';
import { Units } from 'ol/control/ScaleLine';
import { DragBoxEvent } from 'ol/interaction/DragBox';
import { MapService } from './ol/lib/map.service';
import { AppIconDef } from '../icons';
import { LayerWindWeatherComponent } from './ol/lib/resources/layer-wind-weather.component';
import { LayerCurrentsWeatherComponent } from './ol/lib/resources/layer-currents-weather.component';
import { TidalCurrentsLayerComponent } from './ol/lib/resources/tidal-currents-layer.component';
interface IResource {
id: string;
type: string;
}
interface IFeatureData {
aircraft: Map<string, SKAircraft>;
atons: Map<string, SKAtoN>;
sar: Map<string, SKSaR>;
meteo: Map<string, SKMeteo>;
self: SKVessel; //self vessel
ais: Map<string, SKVessel>; // other vessels
active: SKVessel; // focussed vessel
navData: { position: Position; startPosition: Position };
closest: Array<LineString>;
}
enum INTERACTION_MODE {
MEASURE,
DRAW,
MODIFY
}
@Component({
selector: 'fb-map',
imports: [
MatTooltipModule,
MatListModule,
MatIconModule,
MatButtonModule,
MatTooltipModule,
CoordsPipe,
MatCardModule,
MatMenuModule,
FreeboardOpenlayersModule,
PopoverComponent,
FeatureListPopoverComponent,
ChartListPopoverComponent,
AtoNPopoverComponent,
AircraftPopoverComponent,
AlarmPopoverComponent,
ResourcePopoverComponent,
ResourceSetPopoverComponent,
VesselPopoverComponent,
S57PopoverComponent,
LayerWindWeatherComponent,
LayerCurrentsWeatherComponent,
TidalCurrentsLayerComponent
],
templateUrl: './fb-map.component.html',
styleUrls: ['./fb-map.component.css']
})
export class FBMapComponent implements OnInit, OnDestroy {
@Input() setFocus: string;
@Input() mapCenter: Position = [0, 0];
@Input() mapZoom = 1;
@Input() movingMap = false;
@Input() northUp = true;
@Input() measureMode: boolean;
@Input() drawMode: boolean;
@Input() modifyMode = false;
@Input() activeRoute: string;
@Input() vesselTrail: Array<Position> = [];
@Input() dblClickZoom = false;
@Input() overZoomTiles = true;
@Output() drawEnded: EventEmitter<DrawFeatureInfo> = new EventEmitter();
@Output() activate: EventEmitter<string> = new EventEmitter();
@Output() deactivate: EventEmitter<string> = new EventEmitter();
@Output() info: EventEmitter<IResource> = new EventEmitter();
@Output() exitMovingMap: EventEmitter<boolean> = new EventEmitter();
@Output() focusVessel: EventEmitter<string> = new EventEmitter();
@Output() menuItemSelected: EventEmitter<string> = new EventEmitter();
@ViewChild(MatMenuTrigger, { static: true }) contextMenu: MatMenuTrigger;
@ViewChild('olMap', { static: false }) olMap: MapComponent;
scaleUnits = input<string>('');
protected perfLaylines = signal<{
port: MultiLineString;
starboard: MultiLineString;
}>({ port: [], starboard: [] });
protected perfTargetAngle = signal<LineString>([]);
protected vesselLines = signal<{
cog: LineString;
heading: LineString;
}>({
cog: [],
heading: []
});
protected overlay = signal<IPopover>({
id: null,
type: null,
icon: null,
position: [0, 0],
show: false,
title: '',
content: null,
featureCount: 0,
readOnly: false,
isSelf: false
});
protected olMapControls = mapControls;
protected olMapInteractions = signal<Array<{ name: string }>>([]);
protected mapZoomLevel = signal<number>(1);
protected mapCenterPositon = signal<Position>([0, 0]);
protected mapRotation = signal<number>(0);
protected showNoteslayer = signal<boolean>(false); //control notes layer display
// ** map feature styles
protected featureStyles = {
route: routeStyles,
region: regionStyles,
anchor: anchorStyles,
alarm: alarmStyles,
destination: destinationStyles,
aircraft: aircraftStyles,
sar: sarStyles,
layline: laylineStyles,
targetAngle: targetAngleStyle,
raceCourse: raceCourseStyles,
bearingDistance: bearingDistanceStyle
};
// Live route edit buffers (unsaved drafts) rendered via a second fb-routes
// layer in the amber draft style.
protected draftRouteStyles = routeDraftStyles;
protected bufferRoutes = computed<FBRoutes>(() =>
this.routeBuffers
.live()
// A saved + clean route renders from the resource layer (green); only
// unsaved or dirty routes get the amber draft styling.
.filter((b) => !b.saved || b.dirty)
.map((b) => this.bufferToFBRoute(b))
);
// ** map feature data
protected dfeat: IFeatureData = {
aircraft: new Map(),
atons: new Map(),
sar: new Map(),
meteo: new Map(),
self: new SKVessel(), //self vessel
ais: new Map(), // other vessels
active: new SKVessel(), // focussed vessel
navData: { position: null, startPosition: null },
closest: []
};
private saveTimer;
private isDirty = false;
// Cursor position readout. A signal so the readout (and measure overlay)
// refresh when pointer-move runs OUTSIDE the Angular zone (see MapComponent).
protected mouse = signal<{
pixel: number[] | null;
coords: Position;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
xy: any;
}>({
pixel: null,
coords: [0, 0],
xy: null
});
// Bearing/distance/ETA from the vessel to the cursor, shown in the status bar
// when the "Live ETA at cursor" option is enabled (null = hidden).
protected cursorInfo = signal<CursorEtaInfo | null>(null);
contextMenuPosition = { x: '0px', y: '0px' };
// Empty widget-anchor cell at the last right-click (or null) — gates and
// drives the "Add widget here" context-menu item (desktop).
protected addableWidgetCell: ReturnType<
PlotterExtensionService['addableCellAt']
> = null;
private obsList = [];
private http = inject(HttpClient);
protected app = inject(AppFacade);
protected skres = inject(SKResourceService);
protected skresOther = inject(FBCustomResourceService);
protected skstream = inject(SKStreamFacade);
protected anchor = inject(AnchorService);
protected notiMgr = inject(NotificationManager);
protected plotterExt = inject(PlotterExtensionService);
protected course = inject(CourseService);
protected mapInteract = inject(FBMapInteractService);
protected mapService = inject(MapService);
private settings = inject(SettingsFacade);
private bottomSheet = inject(MatBottomSheet);
private infoPanel = inject(InfoPanelFacade);
protected routeBuffers = inject(RouteBufferRegistry);
private ngZone = inject(NgZone);
constructor() {
effect(() => {
if (this.scaleUnits()) {
this.setScaleUnits();
}
});
this.toggleDblClickZoom(); // init olMapinterations
}
ngAfterViewInit() {
this.setScaleUnits();
// ** trigger map focus **
setTimeout(() => {
this.setFocus = 'xxx';
}, 500);
}
ngOnInit() {
// STREAM VESSELS update event
this.obsList.push(
this.skstream.vessels$().subscribe(() => this.onVessels())
);
// SETTINGS settings.change$ event
this.obsList.push(
this.settings.change$.subscribe((r: string[]) => {
this.renderMapContents(r.includes('fetchNotes'));
if (r.includes(`trailFromServer`)) {
if (!this.app.config.vessels.trailFromServer) {
this.app.selfTrailFromServer.update(() => {
return [];
});
}
}
})
);
}
ngOnDestroy() {
this.stopSaveTimer();
this.obsList.forEach((i) => i.unsubscribe());
}
ngOnChanges(changes: SimpleChanges) {
if (changes.vesselTrail) {
this.drawVesselLines();
}
if (changes && changes.mapCenter && changes.mapCenter.currentValue) {
this.mapCenterPositon.set(changes.mapCenter.currentValue);
}
if (
changes &&
changes.mapZoom &&
typeof changes.mapZoom.currentValue === 'number'
) {
this.mapZoomLevel.set(changes.mapZoom.currentValue);
this.renderMapContents(true);
}
if (changes && changes.movingMap && !changes.movingMap.firstChange) {
if (changes.movingMap.currentValue) {
this.startSaveTimer();
} else {
this.stopSaveTimer();
}
this.centerVessel();
}
if (changes && changes.northUp) {
this.rotateMap();
}
if (changes && changes.measureMode) {
this.applyInteractionMode(
INTERACTION_MODE.MEASURE,
changes.measureMode.currentValue
);
}
if (changes && changes.drawMode) {
this.applyInteractionMode(
INTERACTION_MODE.DRAW,
changes.drawMode.currentValue
);
}
if (changes && changes.modifyMode && !changes.modifyMode.firstChange) {
this.applyInteractionMode(
INTERACTION_MODE.MODIFY,
changes.modifyMode.currentValue
);
}
if (changes && changes.dblClickZoom) {
this.toggleDblClickZoom(changes.dblClickZoom.currentValue);
}
}
// set map scale units
private setScaleUnits() {
try {
const u: Units = ['kilometer', 'm'].includes(this.scaleUnits())
? 'metric'
: 'nautical';
const c = this.olMap.getMap().getControls().getArray();
(c[0] as ScaleLine).setUnits(u);
} catch (err) {
// no map or scale control
}
}
// format WMS parameters
protected wmsParams(chart: SKChart) {
return {
LAYERS: chart.layers ? chart.layers.join(',') : ''
};
}
// ** periodically persist state (used in movingMap mode)
private startSaveTimer() {
if (!this.saveTimer) {
this.saveTimer = setInterval(() => {
if (this.isDirty) {
this.app.saveConfig();
this.isDirty = false;
}
}, 30000);
}
}
private stopSaveTimer() {
if (this.saveTimer) {
clearInterval(this.saveTimer);
this.saveTimer = null;
}
}
// ********** EVENT HANDLERS *****************
private onVessels() {
//store last position incase new position is null
const lastPos = this.dfeat.self.position;
this.dfeat.self = this.app.data.vessels.self;
if (!this.dfeat.self.position || !Array.isArray(this.dfeat.self.position)) {
this.dfeat.self.position = lastPos;
}
this.dfeat.ais = this.app.data.vessels.aisTargets;
this.dfeat.aircraft = this.app.data.aircraft;
this.dfeat.sar = this.app.data.sar;
this.dfeat.meteo = this.app.data.meteo;
this.dfeat.atons = this.app.data.atons;
this.dfeat.active = this.app.data.vessels.active;
this.dfeat.navData.position = this.course.courseData().position;
this.dfeat.navData.startPosition = this.course.courseData().startPosition;
// calculate CPA lines
const parseClosest = () => {
const v = [];
if (this.app.data.vessels.self.position) {
this.app.data.vessels.closest.forEach((id: string) => {
if (this.app.data.vessels.aisTargets.has(id)) {
const a = this.app.data.vessels.aisTargets.get(id);
if (a.position) {
v.push([a.position, this.app.data.vessels.self.position]);
}
}
});
}
return v;
};
this.dfeat.closest = parseClosest();
// ** update vessel on map **
if (this.dfeat.self.positionReceived) {
this.app.data.vessels.showSelf = true;
}
// ** locate vessel popover
if (
this.overlay().show &&
['ais', 'aton', 'aircraft'].includes(this.overlay().type)
) {
if (this.overlay().isSelf) {
this.overlay.update((current) => {
return Object.assign({}, current, {
position: this.dfeat.self.position,
vessel: this.dfeat.self
});
});
} else {
if (
(this.overlay().type === 'ais' &&
!this.dfeat.ais.has(this.overlay().id)) ||
(this.overlay().type === 'atons' &&
!this.dfeat.atons.has(this.overlay().id)) ||
(this.overlay().type === 'aircraft' &&
!this.dfeat.aircraft.has(this.overlay().id))
) {
this.overlay().show = false;
} else {
if (this.overlay().type === 'ais') {
this.overlay.update((current) => {
return Object.assign({}, current, {
position: this.dfeat.ais.get(current.id).position,
vessel: this.dfeat.ais.get(current.id)
});
});
}
}
}
if (this.app.mapExtent()[0] < 180 && this.app.mapExtent()[2] > 180) {
// if dateline is in view adjust overlay position to stay with vessel
if (
this.overlay().position[0] < 0 &&
this.overlay().position[0] > -180
) {
this.overlay.update((current) => {
return Object.assign({}, current, {
position: [current.position[0] + 360, current.position[1]]
});
});
}
}
}
this.drawVesselLines(this.app.data.vessels.self.positionReceived);
this.rotateMap();
if (this.movingMap) {
this.centerVessel();
}
}
// ********** RADAR EVENT HANDLERS *****************
handleRadarError(error: Error) {
this.app.showAlert('Radar', error.message);
this.app.uiCtrl.update((current) => {
return Object.assign(current, { radarLayer: false });
});
}
// ********** MAP EVENT HANDLERS *****************
private toggleDblClickZoom(set?: boolean) {
const olInteractions = [
{ name: 'dragpan' },
{ name: 'dragzoom' },
{ name: 'keyboardpan' },
{ name: 'keyboardzoom' },
{ name: 'mousewheelzoom' },
{ name: 'pinchzoom' }
];
this.olMapInteractions.update(() => {
const i = set
? [{ name: 'doubleclickzoom' }].concat(olInteractions)
: [].concat(olInteractions);
return i;
});
}
// ** handle context menu choices **
protected onContextMenuAction(action: string, pos: Position) {
switch (action) {
case 'add_wpt':
this.skres.newWaypointAt(pos);
break;
case 'add_note':
this.skres.showNoteEditor({ position: pos });
break;
case 'nav_to':
this.app.data.activeWaypoint = null;
this.course.courseData().pointNames = [];
this.course.setDestination({
latitude: pos[1],
longitude: pos[0]
});
break;
case 'bearing_dist':
this.formatPopover('bearing_dist', pos);
break;
case 'weather_forecast':
this.bottomSheet.open(WeatherForecastModal, {
disableClose: true,
data: {
title: 'Forecast',
position: pos,
subTitle: 'Location: Cursor Position'
}
});
break;
case 'measure':
this.mapInteract.startMeasuring();
break;
case 'add_widget':
if (this.addableWidgetCell) {
this.plotterExt.openAddWidgetPicker(
this.addableWidgetCell.anchor,
this.addableWidgetCell.cell
);
}
break;
case 'get_feature_info':
this.getFeatureInfo();
break;
default:
this.menuItemSelected.emit(action);
break;
}
}
// handle map move / zoom
protected onMapMoveEnd(e: FBMapEvent) {
this.app.config.map.zoomLevel = e.zoom;
this.app.mapExtent.update(() => e.extent);
this.app.mapViewTopCenter.update(() => e.topCenter as Position);
this.app.mapViewRightCenter.update(() => e.rightCenter as Position);
this.app.mapViewRotation.update(() => e.rotation);
this.app.config.map.center = e.lonlat as Position;
this.drawVesselLines();
if (!this.movingMap) {
// debounce: a flurry of pans/zooms collapses into one save
this.app.saveConfigDebounced();
this.isDirty = false;
} else {
this.isDirty = true;
}
// render map features
this.renderMapContents(e.zoomChanged);
}
// pointer events
protected onMapPointerMove(e: FBPointerEvent) {
this.mouse.set({
pixel: e.pixel,
xy: e.coordinate,
coords: GeoUtils.normaliseCoords(e.lonlat as Position)
});
this.updateCursorInfo(e.lonlat as Position);
if (this.mapInteract.isMeasuring()) {
if (
this.mapInteract.measureGeometryType === 'LineString' &&
this.mapInteract.measurement().coords.length !== 0
) {
const c = e.lonlat;
const lm = this.mapInteract.distanceFromLastPoint(c as Position);
const b = getGreatCircleBearing(
this.mapInteract.measurement().coords.slice(-1)[0],
c as Position
);
this.overlay.update((current) => {
return Object.assign({}, current, {
position: c,
title: `${this.app.formatValueForDisplay(
lm,
'm'
)} ${this.app.formatValueForDisplay(b, 'deg')}`
});
});
} else if (this.mapInteract.measureGeometryType === 'Circle') {
const c = e.lonlat;
const lm = this.mapInteract.distanceFromCenter(c as Position);
const b = getGreatCircleBearing(
this.mapInteract.measurement().center ?? (c as Position),
c as Position
);
this.overlay.update((current) => {
return Object.assign({}, current, {
position: c,
title: `${this.app.formatValueForDisplay(
lm,
'm'
)} ${this.app.formatValueForDisplay(b, 'deg')}`
});
});
}
}
}
protected onMapPointerDrag() {
if (!this.app.config.map.lockMoveMap && this.app.uiConfig().mapMove) {
// pointer-drag runs outside the Angular zone (see MapComponent); re-enter
// so exiting "move map" mode propagates to the UI. Rare one-off transition.
this.ngZone.run(() => this.exitMovingMap.emit(true));
}
}
// Update the status-bar cursor bearing/distance/ETA readout. Off unless the
// "Live ETA at cursor" option is enabled and the vessel position is known.
private updateCursorInfo(cursor: Position) {
const vessel = this.app.data.vessels.self;
if (
!this.app.config.display.statusBar?.liveEta ||
!vessel?.positionReceived ||
!vessel.position
) {
this.cursorInfo.set(null);
return;
}
// referenceSpeed is stored in the user's display speed unit; convert to m/s.
const factor =
Convert.transform(1, 'm/s', this.app.config.units.speed as TARGET_UNIT) ??
1;
const refSpeed = this.app.config.display.statusBar.referenceSpeed;
const referenceSpeedMs =
factor > 0 && typeof refSpeed === 'number' ? refSpeed / factor : 0;
this.cursorInfo.set(
computeCursorEta(vessel.position, cursor, vessel.sog, referenceSpeedMs)
);
}
protected onMapPointerDown(e: FBPointerEvent) {
this.mouse.update((m) => ({
...m,
coords: GeoUtils.normaliseCoords(e.lonlat as Position)
}));
this.contextMenuPosition.x = (e as any).clientX + 'px';
this.contextMenuPosition.y = (e as any).clientY + 'px';
}
protected onMapSingleClick(e) {
this.app.data.map.atClick = {
features: e.features,
lonlat: e.lonlat
};
if (this.mapInteract.isMeasuring()) {
// measuring
this.parseClickInMeasureMode(e.lonlat);
} else if (
// drawing
this.mapInteract.isDrawing() &&
this.mapInteract.draw.resourceType === 'route'
) {
this.onDrawClick(e.features);
} else if (
//not interacting
!this.mapInteract.isDrawing() &&
!this.mapInteract.isModifying()
) {
if (!this.app.config.map.popoverMulti) {
this.overlay.update((current) => {
return Object.assign({}, current, {
show: false
});
});
}
this.processMapClick(e);
}
}
/** Handle right click / touch hold */
protected onMapRightClick(e: { features: FeatureLike[]; lonlat: Position }) {
this.app.data.map.atClick = e;
this.app.debug(`onRightClick()`, this.app.data.map.atClick);
if (this.mapInteract.isMeasuring()) {
this.parseClickInMeasureMode(e.lonlat);
}
}
/** Handle Map context menu event */
protected onMapContextMenu(e: PointerEvent) {
this.app.debug(`onMapContextMenu()`, this.app.data.map.atClick);
this.onContextMenu(e);
}
/** Handle ol-map container context menu event */
protected onContextMenu(e: PointerEvent) {
this.app.debug(`onContextMenu()`, this.app.data.map.atClick);
if (this.app.uiCtrl().suppressContextMenu || this.overlay().show) {
return;
}
e.preventDefault();
this.contextMenuPosition.x = e.clientX + 'px';
this.contextMenuPosition.y = e.clientY + 'px';
// Resolve the click to an empty widget-anchor cell (desktop right-click
// equivalent of the press-and-hold add gesture). Null when not over one.
this.addableWidgetCell = this.plotterExt.addableCellAt(
e.clientX,
e.clientY
);
this.contextMenu.menuData = { item: this.mouse().coords };
if (this.mapInteract.isMeasuring()) {
// The measure point is added by onMapRightClick, which fires alongside
// this handler with a valid lonlat; just suppress the context menu here.
} else if (!this.modifyMode) {
if (!this.mouse().xy) {
return;
}
this.contextMenu.openMenu();
document
.getElementsByClassName('cdk-overlay-backdrop')[0]
.addEventListener('contextmenu', (offEvent) => {
offEvent.preventDefault(); // prevent default context menu for overlay
this.contextMenu.closeMenu();
});
}
}
/** process pointer click event when in measure mode */
private parseClickInMeasureMode(pos: Position) {
if (
this.mapInteract.measureGeometryType === 'LineString' &&
this.mapInteract.measurement().coords.length !== 0
) {
this.onMeasureClick(pos);
}
}
/** Toggle display of chart feature */
protected toggleFeatureSelection(id: string | string[], resType: 'charts') {
if (resType === 'charts') {
this.skres.chartSelected(id);
}
}
/** Handle OL interaction start event */
protected onDragBoxStart(e: DragBoxEvent) {
let c = toLonLat(e.coordinate);
this.mapInteract.initBoxCoord(c as Position);
}
/** Handle OL interaction end event */
protected onDragBoxEnd(e: DragBoxEvent) {
let c = toLonLat(e.coordinate);
this.mapInteract.stopBoxSelection(c as Position);
}
/** Handle OL interaction end event */
protected onDragBoxCancel(e: DragBoxEvent) {
this.app.debug(`onDragBoxCancel()...`);
this.mapInteract.stopBoxSelection();
}
/** Handle OL interaction start event */
protected onMeasureStart(e: DrawEvent) {
this.app.debug(`onMeasureStart()...`, this.mapInteract.measureGeometryType);
let ovPosition: any;
if (this.mapInteract.measureGeometryType === 'LineString') {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let c = (e.feature.getGeometry() as any)
.getCoordinates()
.map((c: Position) => toLonLat(c));
c = c.slice(0, c.length - 1);
this.mapInteract.measurementCoords = c;
ovPosition = c;
} else {
const g = e.feature.getGeometry() as any;
const center = toLonLat(g.getCenter());
const radius = g.getRadius();
this.mapInteract.measurementCenter = center as Position;
this.mapInteract.measurementRadius = radius;
ovPosition = this.mapInteract.measurementCenter;
this.app.debug(this.mapInteract.measurement);
}
this.formatPopover(null, null);
this.overlay.update((current) => {
return Object.assign({}, current, {
position: ovPosition,
title: '0',
show: true,
type: 'measure'
});
});
}
/** Process pointer click in MEASURE mode */
protected onMeasureClick(pt: Position) {
this.app.debug(`onMeasureClick()...`);
if (!Array.isArray(pt)) {
return;
}
const lastPt =
this.mapInteract.measurement().coords[
this.mapInteract.measurement().coords.length - 1
];
if (pt[0] === lastPt[0] && pt[1] === lastPt[1]) {
return;
}
const lm = this.mapInteract.addMeasurementCoord(pt);
// ** update popover measurement values
const c = this.mapInteract.measurement().coords.slice(-2);
const b = getGreatCircleBearing(c[0], c[1]) ?? 0;
this.overlay.update((current) => {
return Object.assign({}, current, {
position: pt,
title: `${this.app.formatValueForDisplay(
lm,
'm'
)} ${this.app.formatValueForDisplay(b, 'deg')}`
});
});
}
/** Handle OL interaction start event */
protected onMeasureEnd() {
this.app.debug(`onMeasureEnd()...`);
this.overlay.update((current) => {
return Object.assign({}, current, {
show: false
});
});
this.mapInteract.stopMeasuring();
}
/**
* Process pointer click in DRAW mode
* @param fa Array of Features
*/
protected onDrawClick(fa: Feature[]) {
if (!Array.isArray(fa)) {
return;
}
if (this.mapInteract.draw.resourceType === 'route') {
let rteCoords: Position[];
fa.forEach((f: Feature) => {
if (f.getGeometry().getType() === 'LineString') {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
rteCoords = (f.getGeometry() as any)
.getCoordinates()
.map((c: Position) => toLonLat(c));
rteCoords = rteCoords.slice(0, rteCoords.length - 1);
}
});
this.mapInteract.measurementCoords = rteCoords;
}
}
/** Handle OL interaction end event */
protected onDrawEnd(e: { feature: Feature }) {
// OL dispatches drawend synchronously from the map's viewport pointer
// handlers, which run outside the Angular zone (see MapComponent). Re-enter
// the zone so the save prompt / live-edit draft opened via
// drawEnded -> handleDrawEnded gets a change-detection pass.
this.ngZone.run(() => {
this.mapInteract.stopDrawing(e.feature);
this.drawEnded.emit(this.mapInteract.draw);
});
}
/** Enter modify mode */
/** Convert a live route edit buffer to the FBRoute tuple fb-routes renders. */
/** The route buffer for `routeId` only when it represents an unsaved draft or
* a route with pending edits. The registry now also mirrors clean saved
* routes, so a plain `routeBuffers.has()` would wrongly treat those as
* unsaved. */
private getUnsavedRouteBuffer(routeId: string): RouteBuffer | undefined {
const b = this.routeBuffers.get(routeId);
return b && (!b.saved || b.dirty) ? b : undefined;
}
private bufferToFBRoute(b: RouteBuffer): FBRoute {
const rte = new SKRoute();
rte.name = b.name ?? '';
rte.description = b.description ?? '';
rte.feature.geometry.coordinates = b.points.map(
(p) => p.position
) as LineString;
// Carry per-point metadata so editing a named draft (which seeds
// coordsMetadata from the rendered feature's pointMetadata) doesn't drop
// waypoint names/descriptions on save.
const coordsMeta = b.points.map((p) => ({
...(p.name ? { name: p.name } : {}),
...(p.description ? { description: p.description } : {})
}));
if (coordsMeta.some((m) => Object.keys(m).length > 0)) {
rte.feature.properties.coordinatesMeta = coordsMeta;
}
rte.distance = GeoUtils.routeLength(rte.feature.geometry.coordinates);
return [b.routeId, rte, true];
}
/** True when the popover's route is an unsaved draft (or has pending edits). */
protected isUnsavedRoute(): boolean {
if (this.overlay().type !== 'route') {
return false;
}
const b = this.routeBuffers.get(this.overlay().id);
return !!b && (!b.saved || b.dirty);
}