-
-
Notifications
You must be signed in to change notification settings - Fork 632
/
camera.ts
1478 lines (1326 loc) · 55.8 KB
/
camera.ts
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 {extend, warnOnce, clamp, wrap, defaultEasing, pick, degreesToRadians} from '../util/util';
import {interpolates} from '@maplibre/maplibre-gl-style-spec';
import {browser} from '../util/browser';
import {LngLat} from '../geo/lng_lat';
import {LngLatBounds} from '../geo/lng_lat_bounds';
import Point from '@mapbox/point-geometry';
import {Event, Evented} from '../util/evented';
import {Terrain} from '../render/terrain';
import {MercatorCoordinate} from '../geo/mercator_coordinate';
import type {Transform} from '../geo/transform';
import type {LngLatLike} from '../geo/lng_lat';
import type {LngLatBoundsLike} from '../geo/lng_lat_bounds';
import type {TaskID} from '../util/task_queue';
import type {PaddingOptions} from '../geo/edge_insets';
/**
* A [Point](https://github.com/mapbox/point-geometry) or an array of two numbers representing `x` and `y` screen coordinates in pixels.
*
* @group Geography and Geometry
*
* @example
* ```ts
* let p1 = new Point(-77, 38); // a PointLike which is a Point
* let p2 = [-77, 38]; // a PointLike which is an array of two numbers
* ```
*/
export type PointLike = Point | [number, number];
/**
* A helper to allow require of at least one propery
*/
export type RequireAtLeastOne<T> = { [K in keyof T]-?: Required<Pick<T, K>> & Partial<Pick<T, Exclude<keyof T, K>>>; }[keyof T];
/**
* Options common to {@link Map#jumpTo}, {@link Map#easeTo}, and {@link Map#flyTo}, controlling the desired location,
* zoom, bearing, and pitch of the camera. All properties are optional, and when a property is omitted, the current
* camera value for that property will remain unchanged.
*
* @example
* Set the map's initial perspective with CameraOptions
* ```ts
* let map = new Map({
* container: 'map',
* style: 'https://demotiles.maplibre.org/style.json',
* center: [-73.5804, 45.53483],
* pitch: 60,
* bearing: -60,
* zoom: 10
* });
* ```
* @see [Set pitch and bearing](https://maplibre.org/maplibre-gl-js/docs/examples/set-perspective/)
* @see [Jump to a series of locations](https://maplibre.org/maplibre-gl-js/docs/examples/jump-to/)
* @see [Fly to a location](https://maplibre.org/maplibre-gl-js/docs/examples/flyto/)
* @see [Display buildings in 3D](https://maplibre.org/maplibre-gl-js/docs/examples/3d-buildings/)
*/
export type CameraOptions = CenterZoomBearing & {
/**
* The desired pitch in degrees. The pitch is the angle towards the horizon
* measured in degrees with a range between 0 and 60 degrees. For example, pitch: 0 provides the appearance
* of looking straight down at the map, while pitch: 60 tilts the user's perspective towards the horizon.
* Increasing the pitch value is often used to display 3D objects.
*/
pitch?: number;
/**
* If `zoom` is specified, `around` determines the point around which the zoom is centered.
*/
around?: LngLatLike;
};
/**
* Holds center, zoom and bearing properties
*/
export type CenterZoomBearing = {
/**
* The desired center.
*/
center?: LngLatLike;
/**
* The desired zoom level.
*/
zoom?: number;
/**
* The desired bearing in degrees. The bearing is the compass direction that
* is "up". For example, `bearing: 90` orients the map so that east is up.
*/
bearing?: number;
}
/**
* The options object related to the {@link Map#jumpTo} method
*/
export type JumpToOptions = CameraOptions & {
/**
* Dimensions in pixels applied on each side of the viewport for shifting the vanishing point.
*/
padding?: PaddingOptions;
}
/**
* A options object for the {@link Map#cameraForBounds} method
*/
export type CameraForBoundsOptions = CameraOptions & {
/**
* The amount of padding in pixels to add to the given bounds.
*/
padding?: number | RequireAtLeastOne<PaddingOptions>;
/**
* The center of the given bounds relative to the map's center, measured in pixels.
* @defaultValue [0, 0]
*/
offset?: PointLike;
/**
* The maximum zoom level to allow when the camera would transition to the specified bounds.
*/
maxZoom?: number;
}
/**
* The {@link Map#flyTo} options object
*/
export type FlyToOptions = AnimationOptions & CameraOptions & {
/**
* The zooming "curve" that will occur along the
* flight path. A high value maximizes zooming for an exaggerated animation, while a low
* value minimizes zooming for an effect closer to {@link Map#easeTo}. 1.42 is the average
* value selected by participants in the user study discussed in
* [van Wijk (2003)](https://www.win.tue.nl/~vanwijk/zoompan.pdf). A value of
* `Math.pow(6, 0.25)` would be equivalent to the root mean squared average velocity. A
* value of 1 would produce a circular motion.
* @defaultValue 1.42
*/
curve?: number;
/**
* The zero-based zoom level at the peak of the flight path. If
* `options.curve` is specified, this option is ignored.
*/
minZoom?: number;
/**
* The average speed of the animation defined in relation to
* `options.curve`. A speed of 1.2 means that the map appears to move along the flight path
* by 1.2 times `options.curve` screenfuls every second. A _screenful_ is the map's visible span.
* It does not correspond to a fixed physical distance, but varies by zoom level.
* @defaultValue 1.2
*/
speed?: number;
/**
* The average speed of the animation measured in screenfuls
* per second, assuming a linear timing curve. If `options.speed` is specified, this option is ignored.
*/
screenSpeed?: number;
/**
* The animation's maximum duration, measured in milliseconds.
* If duration exceeds maximum duration, it resets to 0.
*/
maxDuration?: number;
/**
* The amount of padding in pixels to add to the given bounds.
*/
padding?: number | RequireAtLeastOne<PaddingOptions>;
}
export type EaseToOptions = AnimationOptions & CameraOptions & {
delayEndEvents?: number;
padding?: number | RequireAtLeastOne<PaddingOptions>;
}
/**
* Options for {@link Map#fitBounds} method
*/
export type FitBoundsOptions = FlyToOptions & {
/**
* If `true`, the map transitions using {@link Map#easeTo}. If `false`, the map transitions using {@link Map#flyTo}.
* See those functions and {@link AnimationOptions} for information about options available.
* @defaultValue false
*/
linear?: boolean;
/**
* The center of the given bounds relative to the map's center, measured in pixels.
* @defaultValue [0, 0]
*/
offset?: PointLike;
/**
* The maximum zoom level to allow when the map view transitions to the specified bounds.
*/
maxZoom?: number;
}
/**
* Options common to map movement methods that involve animation, such as {@link Map#panBy} and
* {@link Map#easeTo}, controlling the duration and easing function of the animation. All properties
* are optional.
*
*/
export type AnimationOptions = {
/**
* The animation's duration, measured in milliseconds.
*/
duration?: number;
/**
* A function taking a time in the range 0..1 and returning a number where 0 is
* the initial state and 1 is the final state.
*/
easing?: (_: number) => number;
/**
* of the target center relative to real map container center at the end of animation.
*/
offset?: PointLike;
/**
* If `false`, no animation will occur.
*/
animate?: boolean;
/**
* If `true`, then the animation is considered essential and will not be affected by
* [`prefers-reduced-motion`](https://developer.mozilla.org/en-US/docs/Web/CSS/\@media/prefers-reduced-motion).
*/
essential?: boolean;
/**
* Default false. Needed in 3D maps to let the camera stay in a constant
* height based on sea-level. After the animation finished the zoom-level will be recalculated in respect of
* the distance from the camera to the center-coordinate-altitude.
*/
freezeElevation?: boolean;
};
/**
* A callback hook that allows manipulating the camera and being notified about camera updates before they happen
*/
export type CameraUpdateTransformFunction = (next: {
center: LngLat;
zoom: number;
pitch: number;
bearing: number;
elevation: number;
}) => {
center?: LngLat;
zoom?: number;
pitch?: number;
bearing?: number;
elevation?: number;
};
export abstract class Camera extends Evented {
transform: Transform;
terrain: Terrain;
_moving: boolean;
_zooming: boolean;
_rotating: boolean;
_pitching: boolean;
_padding: boolean;
_bearingSnap: number;
_easeStart: number;
_easeOptions: {
duration?: number;
easing?: (_: number) => number;
};
_easeId: string | void;
_onEaseFrame: (_: number) => void;
_onEaseEnd: (easeId?: string) => void;
_easeFrameId: TaskID;
/**
* @internal
* holds the geographical coordinate of the target
*/
_elevationCenter: LngLat;
/**
* @internal
* holds the targ altitude value, = center elevation of the target.
* This value may changes during flight, because new terrain-tiles loads during flight.
*/
_elevationTarget: number;
/**
* @internal
* holds the start altitude value, = center elevation before animation begins
* this value will recalculated during flight in respect of changing _elevationTarget values,
* so the linear interpolation between start and target keeps smooth and without jumps.
*/
_elevationStart: number;
/**
* @internal
* Saves the current state of the elevation freeze - this is used during map movement to prevent "rocky" camera movement.
*/
_elevationFreeze: boolean;
/**
* @internal
* Used to track accumulated changes during continuous interaction
*/
_requestedCameraState?: Transform;
/**
* A callback used to defer camera updates or apply arbitrary constraints.
* If specified, this Camera instance can be used as a stateless component in React etc.
*/
transformCameraUpdate: CameraUpdateTransformFunction | null;
abstract _requestRenderFrame(a: () => void): TaskID;
abstract _cancelRenderFrame(_: TaskID): void;
constructor(transform: Transform, options: {
bearingSnap: number;
}) {
super();
this._moving = false;
this._zooming = false;
this.transform = transform;
this._bearingSnap = options.bearingSnap;
this.on('moveend', () => {
delete this._requestedCameraState;
});
}
/**
* Returns the map's geographical centerpoint.
*
* @returns The map's geographical centerpoint.
* @example
* Return a LngLat object such as `{lng: 0, lat: 0}`
* ```ts
* let center = map.getCenter();
* // access longitude and latitude values directly
* let {lng, lat} = map.getCenter();
* ```
*/
getCenter(): LngLat { return new LngLat(this.transform.center.lng, this.transform.center.lat); }
/**
* Sets the map's geographical centerpoint. Equivalent to `jumpTo({center: center})`.
*
* Triggers the following events: `movestart` and `moveend`.
*
* @param center - The centerpoint to set.
* @param eventData - Additional properties to be added to event objects of events triggered by this method.
* @example
* ```ts
* map.setCenter([-74, 38]);
* ```
*/
setCenter(center: LngLatLike, eventData?: any) {
return this.jumpTo({center}, eventData);
}
/**
* Pans the map by the specified offset.
*
* Triggers the following events: `movestart` and `moveend`.
*
* @param offset - `x` and `y` coordinates by which to pan the map.
* @param options - Options object
* @param eventData - Additional properties to be added to event objects of events triggered by this method.
* @see [Navigate the map with game-like controls](https://maplibre.org/maplibre-gl-js/docs/examples/game-controls/)
*/
panBy(offset: PointLike, options?: AnimationOptions, eventData?: any): this {
offset = Point.convert(offset).mult(-1);
return this.panTo(this.transform.center, extend({offset}, options), eventData);
}
/**
* Pans the map to the specified location with an animated transition.
*
* Triggers the following events: `movestart` and `moveend`.
*
* @param lnglat - The location to pan the map to.
* @param options - Options describing the destination and animation of the transition.
* @param eventData - Additional properties to be added to event objects of events triggered by this method.
* @example
* ```ts
* map.panTo([-74, 38]);
* // Specify that the panTo animation should last 5000 milliseconds.
* map.panTo([-74, 38], {duration: 5000});
* ```
* @see [Update a feature in realtime](https://maplibre.org/maplibre-gl-js/docs/examples/live-update-feature/)
*/
panTo(lnglat: LngLatLike, options?: AnimationOptions, eventData?: any): this {
return this.easeTo(extend({
center: lnglat
}, options), eventData);
}
/**
* Returns the map's current zoom level.
*
* @returns The map's current zoom level.
* @example
* ```ts
* map.getZoom();
* ```
*/
getZoom(): number { return this.transform.zoom; }
/**
* Sets the map's zoom level. Equivalent to `jumpTo({zoom: zoom})`.
*
* Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, and `zoomend`.
*
* @param zoom - The zoom level to set (0-20).
* @param eventData - Additional properties to be added to event objects of events triggered by this method.
* @example
* Zoom to the zoom level 5 without an animated transition
* ```ts
* map.setZoom(5);
* ```
*/
setZoom(zoom: number, eventData?: any): this {
this.jumpTo({zoom}, eventData);
return this;
}
/**
* Zooms the map to the specified zoom level, with an animated transition.
*
* Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, and `zoomend`.
*
* @param zoom - The zoom level to transition to.
* @param options - Options object
* @param eventData - Additional properties to be added to event objects of events triggered by this method.
* @example
* ```ts
* // Zoom to the zoom level 5 without an animated transition
* map.zoomTo(5);
* // Zoom to the zoom level 8 with an animated transition
* map.zoomTo(8, {
* duration: 2000,
* offset: [100, 50]
* });
* ```
*/
zoomTo(zoom: number, options?: AnimationOptions | null, eventData?: any): this {
return this.easeTo(extend({
zoom
}, options), eventData);
}
/**
* Increases the map's zoom level by 1.
*
* Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, and `zoomend`.
*
* @param options - Options object
* @param eventData - Additional properties to be added to event objects of events triggered by this method.
* @example
* Zoom the map in one level with a custom animation duration
* ```ts
* map.zoomIn({duration: 1000});
* ```
*/
zoomIn(options?: AnimationOptions, eventData?: any): this {
this.zoomTo(this.getZoom() + 1, options, eventData);
return this;
}
/**
* Decreases the map's zoom level by 1.
*
* Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, and `zoomend`.
*
* @param options - Options object
* @param eventData - Additional properties to be added to event objects of events triggered by this method.
* @example
* Zoom the map out one level with a custom animation offset
* ```ts
* map.zoomOut({offset: [80, 60]});
* ```
*/
zoomOut(options?: AnimationOptions, eventData?: any): this {
this.zoomTo(this.getZoom() - 1, options, eventData);
return this;
}
/**
* Returns the map's current bearing. The bearing is the compass direction that is "up"; for example, a bearing
* of 90° orients the map so that east is up.
*
* @returns The map's current bearing.
* @see [Navigate the map with game-like controls](https://maplibre.org/maplibre-gl-js/docs/examples/game-controls/)
*/
getBearing(): number { return this.transform.bearing; }
/**
* Sets the map's bearing (rotation). The bearing is the compass direction that is "up"; for example, a bearing
* of 90° orients the map so that east is up.
*
* Equivalent to `jumpTo({bearing: bearing})`.
*
* Triggers the following events: `movestart`, `moveend`, and `rotate`.
*
* @param bearing - The desired bearing.
* @param eventData - Additional properties to be added to event objects of events triggered by this method.
* @example
* Rotate the map to 90 degrees
* ```ts
* map.setBearing(90);
* ```
*/
setBearing(bearing: number, eventData?: any): this {
this.jumpTo({bearing}, eventData);
return this;
}
/**
* Returns the current padding applied around the map viewport.
*
* @returns The current padding around the map viewport.
*/
getPadding(): PaddingOptions { return this.transform.padding; }
/**
* Sets the padding in pixels around the viewport.
*
* Equivalent to `jumpTo({padding: padding})`.
*
* Triggers the following events: `movestart` and `moveend`.
*
* @param padding - The desired padding.
* @param eventData - Additional properties to be added to event objects of events triggered by this method.
* @example
* Sets a left padding of 300px, and a top padding of 50px
* ```ts
* map.setPadding({ left: 300, top: 50 });
* ```
*/
setPadding(padding: PaddingOptions, eventData?: any): this {
this.jumpTo({padding}, eventData);
return this;
}
/**
* Rotates the map to the specified bearing, with an animated transition. The bearing is the compass direction
* that is "up"; for example, a bearing of 90° orients the map so that east is up.
*
* Triggers the following events: `movestart`, `moveend`, and `rotate`.
*
* @param bearing - The desired bearing.
* @param options - Options object
* @param eventData - Additional properties to be added to event objects of events triggered by this method.
*/
rotateTo(bearing: number, options?: AnimationOptions, eventData?: any): this {
return this.easeTo(extend({
bearing
}, options), eventData);
}
/**
* Rotates the map so that north is up (0° bearing), with an animated transition.
*
* Triggers the following events: `movestart`, `moveend`, and `rotate`.
*
* @param options - Options object
* @param eventData - Additional properties to be added to event objects of events triggered by this method.
*/
resetNorth(options?: AnimationOptions, eventData?: any): this {
this.rotateTo(0, extend({duration: 1000}, options), eventData);
return this;
}
/**
* Rotates and pitches the map so that north is up (0° bearing) and pitch is 0°, with an animated transition.
*
* Triggers the following events: `movestart`, `move`, `moveend`, `pitchstart`, `pitch`, `pitchend`, and `rotate`.
*
* @param options - Options object
* @param eventData - Additional properties to be added to event objects of events triggered by this method.
*/
resetNorthPitch(options?: AnimationOptions, eventData?: any): this {
this.easeTo(extend({
bearing: 0,
pitch: 0,
duration: 1000
}, options), eventData);
return this;
}
/**
* Snaps the map so that north is up (0° bearing), if the current bearing is close enough to it (i.e. within the
* `bearingSnap` threshold).
*
* Triggers the following events: `movestart`, `moveend`, and `rotate`.
*
* @param options - Options object
* @param eventData - Additional properties to be added to event objects of events triggered by this method.
*/
snapToNorth(options?: AnimationOptions, eventData?: any): this {
if (Math.abs(this.getBearing()) < this._bearingSnap) {
return this.resetNorth(options, eventData);
}
return this;
}
/**
* Returns the map's current pitch (tilt).
*
* @returns The map's current pitch, measured in degrees away from the plane of the screen.
*/
getPitch(): number { return this.transform.pitch; }
/**
* Sets the map's pitch (tilt). Equivalent to `jumpTo({pitch: pitch})`.
*
* Triggers the following events: `movestart`, `moveend`, `pitchstart`, and `pitchend`.
*
* @param pitch - The pitch to set, measured in degrees away from the plane of the screen (0-60).
* @param eventData - Additional properties to be added to event objects of events triggered by this method.
*/
setPitch(pitch: number, eventData?: any): this {
this.jumpTo({pitch}, eventData);
return this;
}
/**
* @param bounds - Calculate the center for these bounds in the viewport and use
* the highest zoom level up to and including `Map#getMaxZoom()` that fits
* in the viewport. LngLatBounds represent a box that is always axis-aligned with bearing 0.
* @param options - Options object
* @returns If map is able to fit to provided bounds, returns `center`, `zoom`, and `bearing`.
* If map is unable to fit, method will warn and return undefined.
* @example
* ```ts
* let bbox = [[-79, 43], [-73, 45]];
* let newCameraTransform = map.cameraForBounds(bbox, {
* padding: {top: 10, bottom:25, left: 15, right: 5}
* });
* ```
*/
cameraForBounds(bounds: LngLatBoundsLike, options?: CameraForBoundsOptions): CenterZoomBearing {
bounds = LngLatBounds.convert(bounds);
const bearing = options && options.bearing || 0;
return this._cameraForBoxAndBearing(bounds.getNorthWest(), bounds.getSouthEast(), bearing, options);
}
/**
* @internal
* Calculate the center of these two points in the viewport and use
* the highest zoom level up to and including `Map#getMaxZoom()` that fits
* the points in the viewport at the specified bearing.
* @param p0 - First point
* @param p1 - Second point
* @param bearing - Desired map bearing at end of animation, in degrees
* @param options - the camera options
* @returns If map is able to fit to provided bounds, returns `center`, `zoom`, and `bearing`.
* If map is unable to fit, method will warn and return undefined.
* @example
* ```ts
* let p0 = [-79, 43];
* let p1 = [-73, 45];
* let bearing = 90;
* let newCameraTransform = map._cameraForBoxAndBearing(p0, p1, bearing, {
* padding: {top: 10, bottom:25, left: 15, right: 5}
* });
* ```
*/
_cameraForBoxAndBearing(p0: LngLatLike, p1: LngLatLike, bearing: number, options?: CameraForBoundsOptions): CenterZoomBearing {
const defaultPadding = {
top: 0,
bottom: 0,
right: 0,
left: 0
};
options = extend({
padding: defaultPadding,
offset: [0, 0],
maxZoom: this.transform.maxZoom
}, options);
if (typeof options.padding === 'number') {
const p = options.padding;
options.padding = {
top: p,
bottom: p,
right: p,
left: p
};
}
options.padding = extend(defaultPadding, options.padding) as PaddingOptions;
const tr = this.transform;
const edgePadding = tr.padding;
// Consider all corners of the rotated bounding box derived from the given points
// when find the camera position that fits the given points.
const bounds = new LngLatBounds(p0, p1);
const nwWorld = tr.project(bounds.getNorthWest());
const neWorld = tr.project(bounds.getNorthEast());
const seWorld = tr.project(bounds.getSouthEast());
const swWorld = tr.project(bounds.getSouthWest());
const bearingRadians = degreesToRadians(-bearing);
const nwRotatedWorld = nwWorld.rotate(bearingRadians);
const neRotatedWorld = neWorld.rotate(bearingRadians);
const seRotatedWorld = seWorld.rotate(bearingRadians);
const swRotatedWorld = swWorld.rotate(bearingRadians);
const upperRight = new Point(
Math.max(nwRotatedWorld.x, neRotatedWorld.x, swRotatedWorld.x, seRotatedWorld.x),
Math.max(nwRotatedWorld.y, neRotatedWorld.y, swRotatedWorld.y, seRotatedWorld.y)
);
const lowerLeft = new Point(
Math.min(nwRotatedWorld.x, neRotatedWorld.x, swRotatedWorld.x, seRotatedWorld.x),
Math.min(nwRotatedWorld.y, neRotatedWorld.y, swRotatedWorld.y, seRotatedWorld.y)
);
// Calculate zoom: consider the original bbox and padding.
const size = upperRight.sub(lowerLeft);
const scaleX = (tr.width - (edgePadding.left + edgePadding.right + options.padding.left + options.padding.right)) / size.x;
const scaleY = (tr.height - (edgePadding.top + edgePadding.bottom + options.padding.top + options.padding.bottom)) / size.y;
if (scaleY < 0 || scaleX < 0) {
warnOnce(
'Map cannot fit within canvas with the given bounds, padding, and/or offset.'
);
return undefined;
}
const zoom = Math.min(tr.scaleZoom(tr.scale * Math.min(scaleX, scaleY)), options.maxZoom);
// Calculate center: apply the zoom, the configured offset, as well as offset that exists as a result of padding.
const offset = Point.convert(options.offset);
const paddingOffsetX = (options.padding.left - options.padding.right) / 2;
const paddingOffsetY = (options.padding.top - options.padding.bottom) / 2;
const paddingOffset = new Point(paddingOffsetX, paddingOffsetY);
const rotatedPaddingOffset = paddingOffset.rotate(degreesToRadians(bearing));
const offsetAtInitialZoom = offset.add(rotatedPaddingOffset);
const offsetAtFinalZoom = offsetAtInitialZoom.mult(tr.scale / tr.zoomScale(zoom));
const center = tr.unproject(
// either world diagonal can be used (NW-SE or NE-SW)
nwWorld.add(seWorld).div(2).sub(offsetAtFinalZoom)
);
return {
center,
zoom,
bearing
};
}
/**
* Pans and zooms the map to contain its visible area within the specified geographical bounds.
* This function will also reset the map's bearing to 0 if bearing is nonzero.
*
* Triggers the following events: `movestart` and `moveend`.
*
* @param bounds - Center these bounds in the viewport and use the highest
* zoom level up to and including `Map#getMaxZoom()` that fits them in the viewport.
* @param options - Options supports all properties from {@link AnimationOptions} and {@link CameraOptions} in addition to the fields below.
* @param eventData - Additional properties to be added to event objects of events triggered by this method.
* @example
* ```ts
* let bbox = [[-79, 43], [-73, 45]];
* map.fitBounds(bbox, {
* padding: {top: 10, bottom:25, left: 15, right: 5}
* });
* ```
* @see [Fit a map to a bounding box](https://maplibre.org/maplibre-gl-js/docs/examples/fitbounds/)
*/
fitBounds(bounds: LngLatBoundsLike, options?: FitBoundsOptions, eventData?: any): this {
return this._fitInternal(
this.cameraForBounds(bounds, options),
options,
eventData);
}
/**
* Pans, rotates and zooms the map to to fit the box made by points p0 and p1
* once the map is rotated to the specified bearing. To zoom without rotating,
* pass in the current map bearing.
*
* Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, `zoomend` and `rotate`.
*
* @param p0 - First point on screen, in pixel coordinates
* @param p1 - Second point on screen, in pixel coordinates
* @param bearing - Desired map bearing at end of animation, in degrees
* @param options - Options object
* @param eventData - Additional properties to be added to event objects of events triggered by this method.
* @example
* ```ts
* let p0 = [220, 400];
* let p1 = [500, 900];
* map.fitScreenCoordinates(p0, p1, map.getBearing(), {
* padding: {top: 10, bottom:25, left: 15, right: 5}
* });
* ```
* @see Used by {@link BoxZoomHandler}
*/
fitScreenCoordinates(p0: PointLike, p1: PointLike, bearing: number, options?: FitBoundsOptions, eventData?: any): this {
return this._fitInternal(
this._cameraForBoxAndBearing(
this.transform.pointLocation(Point.convert(p0)),
this.transform.pointLocation(Point.convert(p1)),
bearing,
options),
options,
eventData);
}
_fitInternal(calculatedOptions?: CenterZoomBearing, options?: FitBoundsOptions, eventData?: any): this {
// cameraForBounds warns + returns undefined if unable to fit:
if (!calculatedOptions) return this;
options = extend(calculatedOptions, options);
// Explicitly remove the padding field because, calculatedOptions already accounts for padding by setting zoom and center accordingly.
delete options.padding;
return options.linear ?
this.easeTo(options, eventData) :
this.flyTo(options, eventData);
}
/**
* Changes any combination of center, zoom, bearing, and pitch, without
* an animated transition. The map will retain its current values for any
* details not specified in `options`.
*
* Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, `zoomend`, `pitchstart`,
* `pitch`, `pitchend`, and `rotate`.
*
* @param options - Options object
* @param eventData - Additional properties to be added to event objects of events triggered by this method.
* @example
* ```ts
* // jump to coordinates at current zoom
* map.jumpTo({center: [0, 0]});
* // jump with zoom, pitch, and bearing options
* map.jumpTo({
* center: [0, 0],
* zoom: 8,
* pitch: 45,
* bearing: 90
* });
* ```
* @see [Jump to a series of locations](https://maplibre.org/maplibre-gl-js/docs/examples/jump-to/)
* @see [Update a feature in realtime](https://maplibre.org/maplibre-gl-js/docs/examples/live-update-feature/)
*/
jumpTo(options: JumpToOptions, eventData?: any): this {
this.stop();
const tr = this._getTransformForUpdate();
let zoomChanged = false,
bearingChanged = false,
pitchChanged = false;
if ('zoom' in options && tr.zoom !== +options.zoom) {
zoomChanged = true;
tr.zoom = +options.zoom;
}
if (options.center !== undefined) {
tr.center = LngLat.convert(options.center);
}
if ('bearing' in options && tr.bearing !== +options.bearing) {
bearingChanged = true;
tr.bearing = +options.bearing;
}
if ('pitch' in options && tr.pitch !== +options.pitch) {
pitchChanged = true;
tr.pitch = +options.pitch;
}
if (options.padding != null && !tr.isPaddingEqual(options.padding)) {
tr.padding = options.padding;
}
this._applyUpdatedTransform(tr);
this.fire(new Event('movestart', eventData))
.fire(new Event('move', eventData));
if (zoomChanged) {
this.fire(new Event('zoomstart', eventData))
.fire(new Event('zoom', eventData))
.fire(new Event('zoomend', eventData));
}
if (bearingChanged) {
this.fire(new Event('rotatestart', eventData))
.fire(new Event('rotate', eventData))
.fire(new Event('rotateend', eventData));
}
if (pitchChanged) {
this.fire(new Event('pitchstart', eventData))
.fire(new Event('pitch', eventData))
.fire(new Event('pitchend', eventData));
}
return this.fire(new Event('moveend', eventData));
}
/**
* Calculates pitch, zoom and bearing for looking at `newCenter` with the camera position being `newCenter`
* and returns them as {@link CameraOptions}.
* @param from - The camera to look from
* @param altitudeFrom - The altitude of the camera to look from
* @param to - The center to look at
* @param altitudeTo - Optional altitude of the center to look at. If none given the ground height will be used.
* @returns the calculated camera options
*/
calculateCameraOptionsFromTo(from: LngLat, altitudeFrom: number, to: LngLat, altitudeTo: number = 0): CameraOptions {
const fromMerc = MercatorCoordinate.fromLngLat(from, altitudeFrom);
const toMerc = MercatorCoordinate.fromLngLat(to, altitudeTo);
const dx = toMerc.x - fromMerc.x;
const dy = toMerc.y - fromMerc.y;
const dz = toMerc.z - fromMerc.z;
const distance3D = Math.hypot(dx, dy, dz);
if (distance3D === 0) throw new Error('Can\'t calculate camera options with same From and To');
const groundDistance = Math.hypot(dx, dy);
const zoom = this.transform.scaleZoom(this.transform.cameraToCenterDistance / distance3D / this.transform.tileSize);
const bearing = (Math.atan2(dx, -dy) * 180) / Math.PI;
let pitch = (Math.acos(groundDistance / distance3D) * 180) / Math.PI;
pitch = dz < 0 ? 90 - pitch : 90 + pitch;
return {
center: toMerc.toLngLat(),
zoom,
pitch,
bearing
};
}
/**
* Changes any combination of `center`, `zoom`, `bearing`, `pitch`, and `padding` with an animated transition
* between old and new values. The map will retain its current values for any
* details not specified in `options`.
*
* Note: The transition will happen instantly if the user has enabled
* the `reduced motion` accessibility feature enabled in their operating system,
* unless `options` includes `essential: true`.
*
* Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, `zoomend`, `pitchstart`,
* `pitch`, `pitchend`, and `rotate`.
*
* @param options - Options describing the destination and animation of the transition.
* Accepts {@link CameraOptions} and {@link AnimationOptions}.
* @param eventData - Additional properties to be added to event objects of events triggered by this method.
* @see [Navigate the map with game-like controls](https://maplibre.org/maplibre-gl-js/docs/examples/game-controls/)
*/
easeTo(options: EaseToOptions & {
easeId?: string;
noMoveStart?: boolean;
}, eventData?: any): this {
this._stop(false, options.easeId);
options = extend({
offset: [0, 0],
duration: 500,
easing: defaultEasing
}, options);
if (options.animate === false || (!options.essential && browser.prefersReducedMotion)) options.duration = 0;
const tr = this._getTransformForUpdate(),
startZoom = this.getZoom(),
startBearing = this.getBearing(),
startPitch = this.getPitch(),
startPadding = this.getPadding(),
bearing = 'bearing' in options ? this._normalizeBearing(options.bearing, startBearing) : startBearing,
pitch = 'pitch' in options ? +options.pitch : startPitch,
padding = 'padding' in options ? options.padding : tr.padding;
const offsetAsPoint = Point.convert(options.offset);
let pointAtOffset = tr.centerPoint.add(offsetAsPoint);
const locationAtOffset = tr.pointLocation(pointAtOffset);
const {center, zoom} = tr.getConstrained(
LngLat.convert(options.center || locationAtOffset),
options.zoom ?? startZoom
);
this._normalizeCenter(center);
const from = tr.project(locationAtOffset);
const delta = tr.project(center).sub(from);
const finalScale = tr.zoomScale(zoom - startZoom);
let around, aroundPoint;
if (options.around) {
around = LngLat.convert(options.around);
aroundPoint = tr.locationPoint(around);
}
const currently = {
moving: this._moving,
zooming: this._zooming,
rotating: this._rotating,
pitching: this._pitching
};
this._zooming = this._zooming || (zoom !== startZoom);
this._rotating = this._rotating || (startBearing !== bearing);
this._pitching = this._pitching || (pitch !== startPitch);
this._padding = !tr.isPaddingEqual(padding as PaddingOptions);