-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathmain.js
More file actions
1381 lines (1241 loc) · 47.5 KB
/
Copy pathmain.js
File metadata and controls
1381 lines (1241 loc) · 47.5 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
'use strict';
const projectVersion = require('../package.json').version;
const _ = require('lodash');
const EventEmitter = require('events');
const turfCircle = require('@turf/circle');
const turfBbox = require('@turf/bbox');
const turfBboxPoly = require('@turf/bbox-polygon');
const turfTruncate = require('@turf/truncate');
const turfDestination = require('@turf/destination');
const turfDistance = require('@turf/distance');
const turfBearing = require('@turf/bearing');
const turfHelpers = require('@turf/helpers');
if (window && typeof window.MapboxCircle === 'function') {
throw new TypeError('mapbox-gl-circle-' + window.MapboxCircle.VERSION + ' already loaded');
}
/**
* A `google.maps.Circle` replacement for Mapbox GL JS, rendering a "spherical cap" on top of the world.
* @class MapboxCircle
* @example
* var myCircle = new MapboxCircle({lat: 39.984, lng: -75.343}, 25000, {
* editable: true,
* minRadius: 1500,
* fillColor: '#29AB87'
* }).addTo(myMapboxGlMap);
*
* myCircle.on('centerchanged', function (circleObj) {
* console.log('New center:', circleObj.getCenter());
* });
* myCircle.once('radiuschanged', function (circleObj) {
* console.log('New radius (once!):', circleObj.getRadius());
* });
* myCircle.on('click', function (mapMouseEvent) {
* console.log('Click:', mapMouseEvent.point);
* });
* myCircle.on('contextmenu', function (mapMouseEvent) {
* console.log('Right-click:', mapMouseEvent.lngLat);
* });
* @public
*/
class MapboxCircle {
/**
* @return {string} 'mapbox-gl-circle' library version number.
*/
static get VERSION() {
return projectVersion;
}
/**
* @return {number} Globally unique instance ID.
* @private
*/
get _instanceId() {
if (this.__instanceId === undefined) {
this.__instanceId = MapboxCircle.__MONOSTATE.instanceIdCounter++;
}
return this.__instanceId;
}
/**
* @return {string} Unique circle source ID.
* @private
*/
get _circleSourceId() {
return 'circle-source-' + this._instanceId;
}
/**
* @return {string} Unique circle center handle source ID.
* @private
*/
get _circleCenterHandleSourceId() {
return 'circle-center-handle-source-' + this._instanceId;
}
/**
* @return {string} Unique radius handles source ID.
* @private
*/
get _circleRadiusHandlesSourceId() {
return 'circle-radius-handles-source-' + this._instanceId;
}
/**
* @return {string} Unique circle line-stroke ID.
* @private
*/
get _circleStrokeId() {
return 'circle-stroke-' + this._instanceId;
}
/**
* @return {string} Unique circle fill ID.
* @private
*/
get _circleFillId() {
return 'circle-fill-' + this._instanceId;
}
/**
* @return {string} Unique ID for center handle stroke.
* @private
*/
get _circleCenterHandleStrokeId() {
return 'circle-center-handle-stroke-' + this._instanceId;
}
/**
* @return {string} Unique ID for radius handles stroke.
* @private
*/
get _circleRadiusHandlesStrokeId() {
return 'circle-radius-handles-stroke-' + this._instanceId;
}
/**
* @return {string} Unique circle center handle ID.
* @private
*/
get _circleCenterHandleId() {
return 'circle-center-handle-' + this._instanceId;
}
/**
* @return {string} Unique circle radius handles' ID.
* @private
*/
get _circleRadiusHandlesId() {
return 'circle-radius-handles-' + this._instanceId;
}
/** @param {mapboxgl.Map} map Target map. */
set map(map) {
if (!this._map || !map) {
this._map = map;
} else {
throw new TypeError('MapboxCircle.map reassignment.');
}
}
/** @return {mapboxgl.Map} Mapbox map. */
get map() {
return this._map;
}
/** @param {[number,number]} newCenter Center `[lng, lat]` coordinates. */
set center(newCenter) {
if (this._centerDragActive) {
this._editCenterLngLat[0] = newCenter[0];
this._editCenterLngLat[1] = newCenter[1];
} else {
this._currentCenterLngLat[0] = newCenter[0];
this._currentCenterLngLat[1] = newCenter[1];
}
this._eventEmitter.emit('centerchanging', this);
this._updateCircle();
this._animate();
}
/** @return {[number,number]} Current center `[lng, lat]` coordinates. */
get center() {
return this._centerDragActive ? this._editCenterLngLat : this._currentCenterLngLat;
}
/** @param {number} newRadius Meter radius. */
set radius(newRadius) {
if (this._radiusDragActive) {
this._editRadius = Math.min(Math.max(this.options.minRadius, newRadius), this.options.maxRadius);
} else {
this._currentRadius = Math.min(Math.max(this.options.minRadius, newRadius), this.options.maxRadius);
}
this._eventEmitter.emit('radiuschanging', this);
this._updateCircle();
this._animate();
}
/** @return {number} Current circle radius. */
get radius() {
return this._radiusDragActive ? this._editRadius : this._currentRadius;
}
/** @param {number} newZoom New zoom level. */
set zoom(newZoom) {
this._zoom = newZoom;
if (this.options.refineStroke) {
this._updateCircle();
this._animate();
}
}
/**
* @param {{lat: number, lng: number}|[number,number]} center Circle center as an object or `[lng, lat]` coordinates
* @param {number} radius Meter radius
* @param {?Object} options
* @param {?boolean} [options.editable=false] Enable handles for changing center and radius
* @param {?number} [options.minRadius=10] Minimum radius on user interaction
* @param {?number} [options.maxRadius=1100000] Maximum radius on user interaction
* @param {?string} [options.strokeColor='#000000'] Stroke color
* @param {?number} [options.strokeWeight=0.5] Stroke weight
* @param {?number} [options.strokeOpacity=0.75] Stroke opacity
* @param {?string} [options.fillColor='#FB6A4A'] Fill color
* @param {?number} [options.fillOpacity=0.25] Fill opacity
* @param {?boolean} [options.refineStroke=false] Adjust circle polygon precision based on radius and zoom
* (i.e. prettier circles at the expense of performance)
* @param {?Object} [options.properties={}] Property metadata for Mapbox GL JS circle object
* @public
*/
constructor(center, radius, options) {
/** @const {boolean} */ this.__safariContextMenuEventHackEnabled = false;
/** @const {EventEmitter} */ this._eventEmitter = new EventEmitter();
let centerLat = typeof(center.lat) === 'number' ? center.lat : center[1];
let centerLng = typeof(center.lng) === 'number' ? center.lng : center[0];
/** @const {[number,number]} */ this._lastCenterLngLat = [centerLng, centerLat];
/** @const {[number,number]} */ this._editCenterLngLat = [centerLng, centerLat];
/** @const {[number,number]} */ this._currentCenterLngLat = [centerLng, centerLat];
/** @const {number} */ this._lastRadius = Math.round(radius);
/** @const {number} */ this._editRadius = Math.round(radius);
/** @const {number} */ this._currentRadius = Math.round(radius);
/** @const {Object} */ this.options = _.extend({
editable: false,
strokeColor: '#000000',
strokeWeight: 0.5,
strokeOpacity: 0.75,
fillColor: '#FB6A4A',
fillOpacity: 0.25,
refineStroke: false,
minRadius: 10,
maxRadius: 1.1e6,
properties: {},
debugEl: null
}, options);
/** @const {mapboxgl.Map} */ this._map = undefined;
/** @const {number} */ this._zoom = undefined;
/** @const {Polygon} */ this._circle = undefined;
/** @const {Array<Point>} */ this._handles = undefined;
/** @const {boolean} */ this._centerDragActive = false;
/** @const {boolean} */ this._radiusDragActive = false;
/** @const {Object} */ this._debouncedHandlers = {};
/** @const {number} */ this._updateCount = 0;
[ // Bind all event handlers.
'_onZoomEnd',
'_onCenterHandleMouseEnter',
'_onCenterHandleResumeEvents',
'_onCenterHandleSuspendEvents',
'_onCenterHandleMouseDown',
'_onCenterHandleMouseMove',
'_onCenterHandleMouseUpOrMapMouseOut',
'_onCenterChanged',
'_onCenterHandleMouseLeave',
'_onRadiusHandlesMouseEnter',
'_onRadiusHandlesSuspendEvents',
'_onRadiusHandlesResumeEvents',
'_onRadiusHandlesMouseDown',
'_onRadiusHandlesMouseMove',
'_onRadiusHandlesMouseUpOrMapMouseOut',
'_onRadiusChanged',
'_onRadiusHandlesMouseLeave',
'_onCircleFillMouseMove',
'_onCircleFillSuspendEvents',
'_onCircleFillResumeEvents',
'_onCircleFillContextMenu',
'_onCircleFillClick',
'_onCircleFillMouseLeave',
'_onMapStyleDataLoading'
].forEach((eventHandler) => {
this[eventHandler] = this[eventHandler].bind(this);
});
// Initialize circle.
this._updateCircle();
}
/**
* Return `true` if current browser seems to be Safari.
* @return {boolean}
* @private
*/
static _checkIfBrowserIsSafari() {
return window.navigator.userAgent.indexOf('Chrome') === -1 && window.navigator.userAgent.indexOf('Safari') > -1;
}
/**
* Add debounced event handler to map.
* @param {string} event Mapbox GL event name
* @param {Function} handler Event handler
* @private
*/
_mapOnDebounced(event, handler) {
let ticking = false;
this._debouncedHandlers[handler] = (args) => {
if (!ticking) {
requestAnimationFrame(() => {
handler(args);
ticking = false;
});
}
ticking = true;
};
this.map.on(event, this._debouncedHandlers[handler]);
}
/**
* Remove debounced event handler from map.
* @param {string} event Mapbox GL event name
* @param {Function} handler Event handler
* @private
*/
_mapOffDebounced(event, handler) {
this.map.off(event, this._debouncedHandlers[handler]);
}
/**
* Re-calculate/update circle polygon and handles.
* @private
*/
_updateCircle() {
const center = this.center;
const radius = this.radius;
const zoom = !this._zoom || this._zoom <= 0.1 ? 0.1 : this._zoom;
const steps = this.options.refineStroke ? Math.max((Math.sqrt(Math.trunc(radius * 0.25)) * zoom ^ 2), 64) : 64;
const unit = 'meters';
if (!(this._centerDragActive && radius < 10000)) {
this._circle = turfCircle(center, radius, steps, unit, this.options.properties);
}
if (this.options.editable) {
this._handles = [
turfDestination(center, radius, 0, unit),
turfDestination(center, radius, 90, unit),
turfDestination(center, radius, 180, unit),
turfDestination(center, radius, -90, unit)
];
}
if (this.options.debugEl) {
this._updateCount += 1;
this.options.debugEl.innerHTML = ('Center: ' + JSON.stringify(this.getCenter()) + ' / Radius: ' + radius +
' / Bounds: ' + JSON.stringify(this.getBounds()) + ' / Steps: ' + steps +
' / Zoom: ' + zoom.toFixed(2) + ' / ID: ' + this._instanceId +
' / #: ' + this._updateCount);
}
}
/**
* Return GeoJSON for circle and handles.
* @private
* @return {FeatureCollection}
*/
_getCircleGeoJSON() {
return turfHelpers.featureCollection([this._circle]);
}
/**
* Return GeoJSON for center handle and stroke.
* @private
* @return {FeatureCollection}
*/
_getCenterHandleGeoJSON() {
if (this._centerDragActive && this.radius < 10000) {
return turfHelpers.featureCollection([turfHelpers.point(this.center)]);
} else {
return turfHelpers.featureCollection([turfHelpers.point(this.center), this._circle]);
}
}
/**
* Return GeoJSON for radius handles and stroke.
* @private
* @return {FeatureCollection}
*/
_getRadiusHandlesGeoJSON() {
return turfHelpers.featureCollection([...this._handles, this._circle]);
}
/**
* Refresh map with GeoJSON for circle/handles.
* @private
*/
_animate() {
if (!this._centerDragActive && !this._radiusDragActive) {
this._map.getSource(this._circleSourceId).setData(this._getCircleGeoJSON());
}
if (this.options.editable) {
if (!this._radiusDragActive) {
this._map.getSource(this._circleCenterHandleSourceId).setData(this._getCenterHandleGeoJSON());
}
if (!this._centerDragActive) {
this._map.getSource(this._circleRadiusHandlesSourceId).setData(this._getRadiusHandlesGeoJSON());
}
}
}
/**
* Returns true if cursor point is on a center/radius edit handle.
* @param {{x: number, y: number}} point
* @return {boolean}
* @private
*/
_pointOnHandle(point) {
return !MapboxCircle.__MONOSTATE.activeEditableCircles.every((circleWithHandles) => {
// noinspection JSCheckFunctionSignatures
const handleLayersAtCursor = this.map.queryRenderedFeatures(
point, {layers: [circleWithHandles._circleCenterHandleId, circleWithHandles._circleRadiusHandlesId]});
return handleLayersAtCursor.length === 0;
});
}
/**
* Broadcast suspend event to other interactive circles, instructing them to stop listening during drag interaction.
* @param {string} typeOfHandle 'radius' or 'circle'.
* @private
*/
_suspendHandleListeners(typeOfHandle) {
MapboxCircle.__MONOSTATE.broadcast.emit('suspendCenterHandleListeners', this._instanceId, typeOfHandle);
MapboxCircle.__MONOSTATE.broadcast.emit('suspendRadiusHandlesListeners', this._instanceId, typeOfHandle);
MapboxCircle.__MONOSTATE.broadcast.emit('suspendCircleFillListeners', this._instanceId, typeOfHandle);
}
/**
* Broadcast resume event to other editable circles, to make them to resume interactivity after a completed drag op.
* @param {string} typeOfHandle 'radius' or 'circle'.
* @private
*/
_resumeHandleListeners(typeOfHandle) {
MapboxCircle.__MONOSTATE.broadcast.emit('resumeCenterHandleListeners', this._instanceId, typeOfHandle);
MapboxCircle.__MONOSTATE.broadcast.emit('resumeRadiusHandlesListeners', this._instanceId, typeOfHandle);
MapboxCircle.__MONOSTATE.broadcast.emit('resumeCircleFillListeners', this._instanceId, typeOfHandle);
}
/**
* Disable map panning, set cursor style and highlight handle with new fill color.
* @param {string} layerId
* @param {string} cursor
* @private
*/
_highlightHandles(layerId, cursor) {
this.map.dragPan.disable();
this.map.setPaintProperty(layerId, 'circle-color', this.options.fillColor);
this.map.getCanvas().style.cursor = cursor;
}
/**
* Re-enable map panning, reset cursor icon and restore fill color to white.
* @param {string} layerId
* @private
*/
_resetHandles(layerId) {
this.map.dragPan.enable();
this.map.setPaintProperty(layerId, 'circle-color', '#ffffff');
this.map.getCanvas().style.cursor = '';
}
/**
* Adjust circle precision (steps used to draw the polygon).
* @private
*/
_onZoomEnd() {
this.zoom = this.map.getZoom();
}
/**
* Highlight center handle and disable panning.
* @private
*/
_onCenterHandleMouseEnter() {
this._highlightHandles(this._circleCenterHandleId, 'move');
}
/**
* Stop listening to center handle events, unless it's what the circle is currently busy with.
* @param {number} instanceId ID of the circle instance that requested suspension.
* @param {string} typeOfHandle 'center' or 'radius'.
* @private
*/
_onCenterHandleSuspendEvents(instanceId, typeOfHandle) {
if (instanceId !== this._instanceId || typeOfHandle === 'radius') {
this._unbindCenterHandleListeners();
}
}
/**
* Start listening to center handle events again, unless the circle was NOT among those targeted by suspend event.
* @param {number} instanceId ID of the circle instance that said it's time to resume listening.
* @param {string} typeOfHandle 'center' or 'radius'.
* @private
*/
_onCenterHandleResumeEvents(instanceId, typeOfHandle) {
if (instanceId !== this._instanceId || typeOfHandle === 'radius') {
this._bindCenterHandleListeners();
}
}
/**
* Highlight center handle, disable panning and add mouse-move listener (emulating drag until mouse-up event).
* @private
*/
_onCenterHandleMouseDown() {
if (this._getCursorStyle() !== 'move') {
/* Only trigger center edit event if the user expects it. */ return;
}
this._centerDragActive = true;
this._mapOnDebounced('mousemove', this._onCenterHandleMouseMove);
this.map.addLayer(this._getCenterHandleStrokeLayer(), this._circleCenterHandleId);
this._suspendHandleListeners('center');
this.map.once('mouseup', this._onCenterHandleMouseUpOrMapMouseOut);
this.map.once('mouseout', this._onCenterHandleMouseUpOrMapMouseOut); // Deactivate drag if mouse leaves canvas.
this._highlightHandles(this._circleCenterHandleId, 'move');
}
/**
* Animate circle center change after _onCenterHandleMouseDown triggers.
* @param {MapMouseEvent} event
* @private
*/
_onCenterHandleMouseMove(event) {
const mousePoint = turfTruncate(turfHelpers.point(this.map.unproject(event.point).toArray()), 6);
this.center = mousePoint.geometry.coordinates;
}
/**
* Reset center handle, re-enable panning and remove listeners from _onCenterHandleMouseDown.
* @param {MapMouseEvent} event
* @private
*/
_onCenterHandleMouseUpOrMapMouseOut(event) {
if (event.type === 'mouseout') {
const toMarker = event.originalEvent.toElement.classList.contains('mapboxgl-marker');
const fromCanvas = event.originalEvent.fromElement.classList.contains('mapboxgl-canvas');
const toCanvas = event.originalEvent.toElement.classList.contains('mapboxgl-canvas');
const fromMarker = event.originalEvent.fromElement.classList.contains('mapboxgl-marker');
if ((fromCanvas && toMarker) || (fromMarker && toCanvas)) {
this.map.once('mouseout', this._onCenterHandleMouseUpOrMapMouseOut); // Add back 'once' handler.
return;
}
}
const newCenter = this.center;
this._centerDragActive = false;
this._mapOffDebounced('mousemove', this._onCenterHandleMouseMove);
switch (event.type) {
case 'mouseup': this.map.off('mouseout', this._onCenterHandleMouseUpOrMapMouseOut); break;
case 'mouseout': this.map.off('mouseup', this._onCenterHandleMouseUpOrMapMouseOut); break;
}
this._resumeHandleListeners('center');
this.map.removeLayer(this._circleCenterHandleStrokeId);
this._resetHandles(this._circleCenterHandleId);
if (newCenter[0] !== this._lastCenterLngLat[0] || newCenter[1] !== this._lastCenterLngLat[1]) {
this.center = newCenter;
this._eventEmitter.emit('centerchanged', this);
}
}
/**
* Update _lastCenterLngLat on `centerchanged` event.
* @private
*/
_onCenterChanged() {
this._lastCenterLngLat[0] = this.center[0];
this._lastCenterLngLat[1] = this.center[1];
}
/**
* Reset center handle and re-enable panning, unless actively dragging.
* @private
*/
_onCenterHandleMouseLeave() {
if (this._centerDragActive) {
setTimeout(() => { // If dragging, wait a bit to see if it just recently stopped.
if (!this._centerDragActive) this._resetHandles(this._circleCenterHandleId);
}, 125);
} else {
this._resetHandles(this._circleCenterHandleId);
}
}
/**
* Return vertical or horizontal resize arrow depending on if mouse is at left-right or top-bottom edit handles.
* @param {MapMouseEvent} event
* @return {string} 'ew-resize' or 'ns-resize'
* @private
*/
_getRadiusHandleCursorStyle(event) {
const bearing = turfBearing(event.lngLat.toArray(), this._currentCenterLngLat, true);
if (bearing > 270+45 || bearing <= 45) { // South.
return 'ns-resize';
}
if (bearing > 45 && bearing <= 90+45) { // West.
return 'ew-resize';
}
if (bearing > 90+45 && bearing <= 180+45) { // North.
return 'ns-resize';
}
if (bearing > 270-45 && bearing <= 270+45) { // East.
return 'ew-resize';
}
}
/**
* Highlight radius handles and disable panning.
* @param {MapMouseEvent} event
* @private
*/
_onRadiusHandlesMouseEnter(event) {
this._highlightHandles(this._circleRadiusHandlesId, this._getRadiusHandleCursorStyle(event));
}
/**
* Stop listening to radius handles' events, unless it's what the circle is currently busy with.
* @param {number} instanceId ID of the circle instance that requested suspension.
* @param {string} typeOfHandle 'center' or 'radius'.
* @private
*/
_onRadiusHandlesSuspendEvents(instanceId, typeOfHandle) {
if (instanceId !== this._instanceId || typeOfHandle === 'center') {
this._unbindRadiusHandlesListeners();
}
}
/**
* Start listening to radius handles' events again, unless the circle was NOT among those targeted by suspend event.
* @param {number} instanceId ID of the circle instance that said it's time to resume listening.
* @param {string} typeOfHandle 'center' or 'radius'.
* @private
*/
_onRadiusHandlesResumeEvents(instanceId, typeOfHandle) {
if (instanceId !== this._instanceId || typeOfHandle === 'center') {
this._bindRadiusHandlesListeners();
}
}
/**
* Highlight radius handles, disable panning and add mouse-move listener (emulating drag until mouse-up event).
* @param {MapMouseEvent} event
* @private
*/
_onRadiusHandlesMouseDown(event) {
if (!this._getCursorStyle().endsWith('-resize')) {
/* Only trigger radius edit event if the user expects it. */ return;
}
this._radiusDragActive = true;
this._mapOnDebounced('mousemove', this._onRadiusHandlesMouseMove);
this.map.addLayer(this._getRadiusHandlesStrokeLayer(), this._circleRadiusHandlesId);
this._suspendHandleListeners('radius');
this.map.once('mouseup', this._onRadiusHandlesMouseUpOrMapMouseOut);
this.map.once('mouseout', this._onRadiusHandlesMouseUpOrMapMouseOut); // Deactivate drag if mouse leaves canvas.
this._highlightHandles(this._circleRadiusHandlesId, this._getRadiusHandleCursorStyle(event));
}
/**
* Animate circle radius change after _onRadiusHandlesMouseDown triggers.
* @param {MapMouseEvent} event
* @private
*/
_onRadiusHandlesMouseMove(event) {
const mousePoint = this.map.unproject(event.point).toArray();
this.radius = Math.round(turfDistance(this.center, mousePoint, 'meters'));
}
/**
* Reset radius handles, re-enable panning and remove listeners from _onRadiusHandlesMouseDown.
* @param {MapMouseEvent} event
* @private
*/
_onRadiusHandlesMouseUpOrMapMouseOut(event) {
if (event.type === 'mouseout') {
const toMarker = event.originalEvent.toElement.classList.contains('mapboxgl-marker');
const fromCanvas = event.originalEvent.fromElement.classList.contains('mapboxgl-canvas');
const toCanvas = event.originalEvent.toElement.classList.contains('mapboxgl-canvas');
const fromMarker = event.originalEvent.fromElement.classList.contains('mapboxgl-marker');
if ((fromCanvas && toMarker) || (fromMarker && toCanvas)) {
this.map.once('mouseout', this._onRadiusHandlesMouseUpOrMapMouseOut); // Add back 'once' handler.
return;
}
}
const newRadius = this.radius;
this._radiusDragActive = false;
this._mapOffDebounced('mousemove', this._onRadiusHandlesMouseMove);
this.map.removeLayer(this._circleRadiusHandlesStrokeId);
switch (event.type) {
case 'mouseup': this.map.off('mouseout', this._onRadiusHandlesMouseUpOrMapMouseOut); break;
case 'mouseout': this.map.off('mouseup', this._onRadiusHandlesMouseUpOrMapMouseOut); break;
}
this._resumeHandleListeners('radius');
this._resetHandles(this._circleRadiusHandlesId);
if (newRadius !== this._lastRadius) {
this.radius = newRadius;
this._eventEmitter.emit('radiuschanged', this);
}
}
/**
* Update _lastRadius on `radiuschanged` event.
* @private
*/
_onRadiusChanged() {
this._lastRadius = this.radius;
}
/**
* Reset radius handles and re-enable panning, unless actively dragging.
* @private
*/
_onRadiusHandlesMouseLeave() {
if (this._radiusDragActive) {
setTimeout(() => { // If dragging, wait a bit to see if it just recently stopped.
if (!this._radiusDragActive) this._resetHandles(this._circleRadiusHandlesId);
}, 125);
} else {
this._resetHandles(this._circleRadiusHandlesId);
}
}
/**
* Set pointer cursor when moving over circle fill, and it's clickable.
* @param {MapMouseEvent} event
* @private
*/
_onCircleFillMouseMove(event) {
if (this._eventEmitter.listeners('click').length > 0 && !this._pointOnHandle(event.point)) {
event.target.getCanvas().style.cursor = 'pointer';
}
}
/**
* Stop listening to circle fill events.
* @private
*/
_onCircleFillSuspendEvents() {
this._unbindCircleFillListeners();
}
/**
* Start listening to circle fill events again.
* @private
*/
_onCircleFillResumeEvents() {
this._bindCircleFillListeners();
}
/**
* Fire 'contextmenu' event.
* @param {MapMouseEvent} event
* @private
*/
_onCircleFillContextMenu(event) {
if (this._pointOnHandle(event.point)) {
/* No click events while on a center/radius edit handle. */ return;
}
if (event.originalEvent.ctrlKey && MapboxCircle._checkIfBrowserIsSafari()) {
// This hack comes from SPFAM-1090, aimed towards eliminating the extra 'click' event that's
// emitted by Safari when performing a right-click by holding the ctrl button.
this.__safariContextMenuEventHackEnabled = true;
} else {
this._eventEmitter.emit('contextmenu', event);
}
}
/**
* Fire 'click' event.
* @param {MapMouseEvent} event
* @private
*/
_onCircleFillClick(event) {
if (this._pointOnHandle(event.point)) {
/* No click events while on a center/radius edit handle. */ return;
}
if (!this.__safariContextMenuEventHackEnabled) {
this._eventEmitter.emit('click', event);
} else {
this._eventEmitter.emit('contextmenu', event);
this.__safariContextMenuEventHackEnabled = false;
}
}
/**
* Remove pointer cursor when leaving circle fill.
* @param {MapMouseEvent} event
* @private
*/
_onCircleFillMouseLeave(event) {
if (this._eventEmitter.listeners('click').length > 0 && !this._pointOnHandle(event.point)) {
event.target.getCanvas().style.cursor = '';
}
}
/**
* When map style is changed, remove circle assets from map and add it back on next MapboxGL 'styledata' event.
* @param {MapDataEvent} event
* @private
*/
_onMapStyleDataLoading(event) {
if (this.map) {
this.map.once('styledata', () => {
// noinspection JSUnresolvedVariable
this.addTo(event.target);
});
this.remove();
}
}
/**
* Add all static listeners for center handle.
* @param {mapboxgl.Map} [map]
* @private
*/
_bindCenterHandleListeners(map) {
map = map || this.map;
const layerId = this._circleCenterHandleId;
map.on('mouseenter', layerId, this._onCenterHandleMouseEnter);
map.on('mousedown', layerId, this._onCenterHandleMouseDown);
map.on('mouseleave', layerId, this._onCenterHandleMouseLeave);
}
/**
* Remove all static listeners for center handle.
* @param {mapboxgl.Map} [map]
* @private
*/
_unbindCenterHandleListeners(map) {
map = map || this.map;
const layerId = this._circleCenterHandleId;
map.off('mouseenter', layerId, this._onCenterHandleMouseEnter);
map.off('mousedown', layerId, this._onCenterHandleMouseDown);
map.off('mouseleave', layerId, this._onCenterHandleMouseLeave);
}
/**
* Add all static listeners for radius handles.
* @param {mapboxgl.Map} [map]
* @private
*/
_bindRadiusHandlesListeners(map) {
map = map || this.map;
const layerId = this._circleRadiusHandlesId;
map.on('mouseenter', layerId, this._onRadiusHandlesMouseEnter);
map.on('mousedown', layerId, this._onRadiusHandlesMouseDown);
map.on('mouseleave', layerId, this._onRadiusHandlesMouseLeave);
}
/**
* Remove all static listeners for radius handles.
* @param {mapboxgl.Map} [map]
* @private
*/
_unbindRadiusHandlesListeners(map) {
map = map || this.map;
const layerId = this._circleRadiusHandlesId;
map.off('mouseenter', layerId, this._onRadiusHandlesMouseEnter);
map.off('mousedown', layerId, this._onRadiusHandlesMouseDown);
map.off('mouseleave', layerId, this._onRadiusHandlesMouseLeave);
}
/**
* Add all click/contextmenu listeners for circle fill layer.
* @param {mapboxgl.Map} [map]
* @private
*/
_bindCircleFillListeners(map) {
map = map || this.map;
const layerId = this._circleFillId;
map.on('click', layerId, this._onCircleFillClick);
map.on('contextmenu', layerId, this._onCircleFillContextMenu);
map.on('mousemove', layerId, this._onCircleFillMouseMove);
map.on('mouseleave', layerId, this._onCircleFillMouseLeave);
}
/**
* Remove all click/contextmenu listeners for circle fill.
* @param {mapboxgl.Map} [map]
* @private
*/
_unbindCircleFillListeners(map) {
map = map || this.map;
const layerId = this._circleFillId;
map.off('click', layerId, this._onCircleFillClick);
map.off('contextmenu', layerId, this._onCircleFillContextMenu);
map.off('mousemove', layerId, this._onCircleFillMouseMove);
map.off('mouseleave', layerId, this._onCircleFillMouseLeave);
}
/**
* Add suspend/resume listeners for `__MONOSTATE.broadcast` event emitter.
* @private
*/
_bindBroadcastListeners() {
MapboxCircle.__MONOSTATE.broadcast.on('suspendCenterHandleListeners', this._onCenterHandleSuspendEvents);
MapboxCircle.__MONOSTATE.broadcast.on('resumeCenterHandleListeners', this._onCenterHandleResumeEvents);
MapboxCircle.__MONOSTATE.broadcast.on('suspendRadiusHandlesListeners', this._onRadiusHandlesSuspendEvents);
MapboxCircle.__MONOSTATE.broadcast.on('resumeRadiusHandlesListeners', this._onRadiusHandlesResumeEvents);
MapboxCircle.__MONOSTATE.broadcast.on('suspendCircleFillListeners', this._onCircleFillSuspendEvents);
MapboxCircle.__MONOSTATE.broadcast.on('resumeCircleFillListeners', this._onCircleFillResumeEvents);
}
/**
* Remove suspend/resume handlers from `__MONOSTATE.broadcast` emitter.
* @private
*/
_unbindBroadcastListeners() {
MapboxCircle.__MONOSTATE.broadcast.removeListener(
'suspendCenterHandleListeners', this._onCenterHandleSuspendEvents);
MapboxCircle.__MONOSTATE.broadcast.removeListener(
'resumeCenterHandleListeners', this._onCenterHandleResumeEvents);
MapboxCircle.__MONOSTATE.broadcast.removeListener(
'suspendRadiusHandlesListeners', this._onRadiusHandlesSuspendEvents);
MapboxCircle.__MONOSTATE.broadcast.removeListener(
'resumeRadiusHandlesListeners', this._onRadiusHandlesResumeEvents);
MapboxCircle.__MONOSTATE.broadcast.removeListener(
'suspendCircleFillListeners', this._onCircleFillSuspendEvents);
MapboxCircle.__MONOSTATE.broadcast.removeListener(
'resumeCircleFillListeners', this._onCircleFillResumeEvents);
}
/**
* Add circle to `__MONOSTATE.activeEditableCircles` array and increase max broadcasting listeners by 1.
* @param {MapboxCircle} circleObject
* @private
*/
static _addActiveEditableCircle(circleObject) {
MapboxCircle.__MONOSTATE.activeEditableCircles.push(circleObject);
MapboxCircle.__MONOSTATE.broadcast.setMaxListeners(
MapboxCircle.__MONOSTATE.activeEditableCircles.length);
}
/**
* Remove circle from `__MONOSTATE.activeEditableCircles` array and decrease max broadcasting listeners by 1.
* @param {MapboxCircle} circleObject
* @private
*/
static _removeActiveEditableCircle(circleObject) {
MapboxCircle.__MONOSTATE.activeEditableCircles.splice(
MapboxCircle.__MONOSTATE.activeEditableCircles.indexOf(circleObject), 1);
MapboxCircle.__MONOSTATE.broadcast.setMaxListeners(
MapboxCircle.__MONOSTATE.activeEditableCircles.length);
}
/**
* @return {Object} GeoJSON map source for the circle.
* @private
*/
_getCircleMapSource() {
return {
type: 'geojson',
data: this._getCircleGeoJSON(),
buffer: 1
};
}
/**
* @return {Object} GeoJSON map source for center handle.
* @private
*/
_getCenterHandleMapSource() {
return {
type: 'geojson',
data: this._getCenterHandleGeoJSON(),
buffer: 1
};
}
/**
* @return {Object} GeoJSON map source for radius handles.
* @private
*/
_getRadiusHandlesMapSource() {
return {
type: 'geojson',
data: this._getRadiusHandlesGeoJSON(),
buffer: 1
};
}
/**
* @return {Object} Style layer for the stroke around the circle.
* @private
*/
_getCircleStrokeLayer() {
return {
id: this._circleStrokeId,
type: 'line',
source: this._circleSourceId,