-
-
Notifications
You must be signed in to change notification settings - Fork 937
Expand file tree
/
Copy pathMapView.tsx
More file actions
1321 lines (1172 loc) · 39.3 KB
/
MapView.tsx
File metadata and controls
1321 lines (1172 loc) · 39.3 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 React, { Component } from 'react';
import {
View,
StyleSheet,
NativeModules,
ViewProps,
NativeSyntheticEvent,
NativeMethods,
HostComponent,
LayoutChangeEvent,
} from 'react-native';
import debounce from 'debounce';
import NativeMapView, {
type NativeMapViewActual,
} from '../specs/RNMBXMapViewNativeComponent';
import NativeMapViewModule from '../specs/NativeMapViewModule';
import {
isFunction,
isAndroid,
type NativeArg,
type OrnamentPositonProp,
} from '../utils';
import { getFilter } from '../utils/filterUtils';
import Logger from '../utils/Logger';
import type { FilterExpression } from '../utils/MapboxStyles';
import { type Position } from '../types/Position';
import { type Location } from '../modules/location/locationManager';
import NativeBridgeComponent from './NativeBridgeComponent';
const { RNMBXModule } = NativeModules;
const { EventTypes } = RNMBXModule;
if (RNMBXModule == null) {
console.error(
'Native part of Mapbox React Native libraries were not registered properly, double check our native installation guides.',
);
}
if (!RNMBXModule.MapboxV10) {
console.warn(
'@rnmapbox/maps: Non v10 implementations are deprecated and will be removed in next version - see https://github.com/rnmapbox/maps/wiki/Deprecated-RNMapboxImpl-Maplibre',
);
}
const styles = StyleSheet.create({
matchParent: { flex: 1 },
});
const defaultStyleURL = RNMBXModule.StyleURL.Street;
export type Point = {
x: number;
y: number;
};
type BBox = [number, number, number, number];
export type RegionPayload = {
zoomLevel: number;
heading: number;
animated: boolean;
isUserInteraction: boolean;
visibleBounds: GeoJSON.Position[];
pitch: number;
};
export type GestureSettings = {
/**
* Whether double tapping the map with one touch results in a zoom-in animation.
*/
doubleTapToZoomInEnabled?: boolean;
/**
* Whether single tapping the map with two touches results in a zoom-out animation.
*/
doubleTouchToZoomOutEnabled?: boolean;
/**
* By default, gestures rotate and zoom around the center of the gesture. Set
* this property to rotate and zoom around a fixed point instead.
*/
focalPoint?: Point;
/**
* Whether pan/scroll is enabled for the pinch gesture.
*/
pinchPanEnabled?: boolean;
/**
* Whether zoom is enabled for the pinch gesture.
*/
pinchZoomEnabled?: boolean;
/**
* Whether a deceleration animation following a pinch-zoom gesture is enabled. True by default.
* (Android only)
*/
pinchZoomDecelerationEnabled?: boolean;
/**
* Whether the pitch gesture is enabled.
*/
pitchEnabled?: boolean;
/**
* Whether the quick zoom gesture is enabled.
*/
quickZoomEnabled?: boolean;
/**
* Whether the rotate gesture is enabled.
*/
rotateEnabled?: boolean;
/**
* Whether a deceleration animation following a rotate gesture is enabled. True by default.
* (Android only)
*/
rotateDecelerationEnabled?: boolean;
/**
* Whether the single-touch pan/scroll gesture is enabled.
*/
panEnabled?: boolean;
/**
* A constant factor that determines how quickly pan deceleration animations happen. Multiplied with the velocity vector once per millisecond during deceleration animations.
*
* On iOS Defaults to UIScrollView.DecelerationRate.normal.rawValue
* On android set to 0 to disable deceleration, and non zero to enabled it.
*/
panDecelerationFactor?: number;
/**
* Whether rotation is enabled for the pinch zoom gesture.
*/
simultaneousRotateAndPinchZoomEnabled?: boolean;
/**
* The amount by which the zoom level increases or decreases during a double-tap-to-zoom-in or double-touch-to-zoom-out gesture. 1.0 by default. Must be positive.
* (Android only)
*/
zoomAnimationAmount?: number;
};
/**
* v10 only
*/
export type MapState = {
properties: {
center: GeoJSON.Position;
bounds: {
ne: GeoJSON.Position;
sw: GeoJSON.Position;
};
zoom: number;
heading: number;
pitch: number;
};
gestures: {
isGestureActive: boolean;
};
timestamp?: number;
};
/**
* label localization settings (v10 only). `true` is equivalent to current locale.
*/
type LocalizeLabels =
| {
/** locale code like `es` or `current` for the device's current locale */
locale: string;
/** layer id to localize. If not specified, all layers will be localized */
layerIds?: string[];
}
| true;
type Props = ViewProps & {
/**
* The distance from the edges of the map view’s frame to the edges of the map view’s logical viewport.
* @deprecated use Camera `padding` instead
*/
contentInset?: number | number[];
/**
* The projection used when rendering the map
*/
projection?: 'mercator' | 'globe';
/**
* Style URL for map - notice, if non is set it _will_ default to `Mapbox.StyleURL.Street`
*/
styleURL?: string;
/**
* StyleJSON for map - according to TileJSON specs: https://github.com/mapbox/tilejson-spec
*/
styleJSON?: string;
/**
* iOS: The preferred frame rate at which the map view is rendered.
* The default value for this property is MGLMapViewPreferredFramesPerSecondDefault,
* which will adaptively set the preferred frame rate based on the capability of
* the user’s device to maintain a smooth experience. This property can be set to arbitrary integer values.
*
* Android: The maximum frame rate at which the map view is rendered, but it can't exceed the ability of device hardware.
* This property can be set to arbitrary integer values.
*/
preferredFramesPerSecond?: number;
/**
* Enable/Disable zoom on the map
*/
zoomEnabled?: boolean;
/**
* Enable/Disable scroll on the map
*/
scrollEnabled?: boolean;
/**
* Enable/Disable pitch on map
*/
pitchEnabled?: boolean;
/**
* Maximum allowed pitch in degrees. Mirrors the Mapbox map option `maxPitch`.
*/
maxPitch?: number;
/**
* Enable/Disable rotation on map
*/
rotateEnabled?: boolean;
/**
* The Mapbox terms of service, which governs the use of Mapbox-hosted vector tiles and styles,
* [requires](https://www.mapbox.com/help/how-attribution-works/) these copyright notices to accompany any map that features Mapbox-designed styles, OpenStreetMap data, or other Mapbox data such as satellite or terrain data.
* If that applies to this map view, do not hide this view or remove any notices from it.
*
* You are additionally [required](https://www.mapbox.com/help/how-mobile-apps-work/#telemetry) to provide users with the option to disable anonymous usage and location sharing (telemetry).
* If this view is hidden, you must implement this setting elsewhere in your app. See our website for [Android](https://www.mapbox.com/android-docs/map-sdk/overview/#telemetry-opt-out) and [iOS](https://www.mapbox.com/ios-sdk/#telemetry_opt_out) for implementation details.
*
* Enable/Disable attribution on map. For iOS you need to add MGLMapboxMetricsEnabledSettingShownInApp=YES
* to your Info.plist
*/
attributionEnabled?: boolean;
/**
* Adds attribution offset, e.g. `{top: 8, left: 8}` will put attribution button in top-left corner of the map. By default on Android, the attribution with information icon (i) will be on the bottom left, while on iOS the mapbox logo will be on bottom left with information icon (i) on bottom right. Read more about mapbox attribution [here](https://docs.mapbox.com/help/getting-started/attribution/)
*/
attributionPosition?: OrnamentPositonProp;
/**
* MapView's tintColor
*/
tintColor?: string | number[];
/**
* Enable/Disable the logo on the map.
*/
logoEnabled?: boolean;
/**
* Adds logo offset, e.g. `{top: 8, left: 8}` will put the logo in top-left corner of the map
*/
logoPosition?: OrnamentPositonProp;
/**
* Enable/Disable the compass from appearing on the map
*/
compassEnabled?: boolean;
/**
* [`mapbox` (v10) implementation only] Enable/Disable if the compass should fade out when the map is pointing north
*/
compassFadeWhenNorth?: boolean;
/**
* [`mapbox` (v10) implementation only] Adds compass offset, e.g. `{top: 8, left: 8}` will put the compass in top-left corner of the map
*/
compassPosition?: OrnamentPositonProp;
/**
* Change corner of map the compass starts at. 0: TopLeft, 1: TopRight, 2: BottomLeft, 3: BottomRight
*/
compassViewPosition?: number;
/**
* Add margins to the compass with x and y values
*/
compassViewMargins?: Point;
/**
* [iOS, `mapbox` (v10) implementation only] A string referencing an image key. Requires an `Images` component.
*/
compassImage?: string;
/**
* [`mapbox` (v10) implementation only] Enable/Disable the scale bar from appearing on the map
*/
scaleBarEnabled?: boolean;
/**
* [`mapbox` (v10) implementation only] Adds scale bar offset, e.g. `{top: 8, left: 8}` will put the scale bar in top-left corner of the map
*/
scaleBarPosition?: OrnamentPositonProp;
/**
* [Android only] Enable/Disable use of GLSurfaceView instead of TextureView.
*/
surfaceView?: boolean;
/**
* [Android only] Experimental, call requestDisallowInterceptTouchEvent on parent with onTochEvent, this allows touch interaction to work
* when embedded into a scroll view
*/
requestDisallowInterceptTouchEvent?: boolean;
/**
* [`mapbox` (v10) implementation only]
* Set map's label locale, e.g. `{ "locale": "es" }` will localize labels to Spanish, `{ "locale": "current" }` will localize labels to system locale.
*/
localizeLabels?: LocalizeLabels;
/**
* Gesture configuration allows to control the user touch interaction.
*/
gestureSettings?: GestureSettings;
/**
* Map press listener, gets called when a user presses the map
*/
onPress?: (feature: GeoJSON.Feature) => void;
/**
* Map long press listener, gets called when a user long presses the map
*/
onLongPress?: (feature: GeoJSON.Feature) => void;
/**
* <v10 only
*
* This event is triggered whenever the currently displayed map region is about to change.
*
* @param {PointFeature} feature - The geojson point feature at the camera center, properties contains zoomLevel, visibleBounds
*/
onRegionWillChange?: (
feature: GeoJSON.Feature<GeoJSON.Point, RegionPayload>,
) => void;
/**
*
* This event is triggered whenever the currently displayed map region is changing.
*
* @param {PointFeature} feature - The geojson point feature at the camera center, properties contains zoomLevel, visibleBounds
*/
onRegionIsChanging?: (
feature: GeoJSON.Feature<GeoJSON.Point, RegionPayload>,
) => void;
/**
*
* This event is triggered whenever the currently displayed map region finished changing.
*
* @param {PointFeature} feature - The geojson point feature at the camera center, properties contains zoomLevel, visibleBounds
*/
onRegionDidChange?: (
feature: GeoJSON.Feature<GeoJSON.Point, RegionPayload>,
) => void;
/**
* v10 only, replaces onRegionIsChanging
*/
onCameraChanged?: (state: MapState) => void;
/**
* v10 only, replaces onRegionDidChange
*/
onMapIdle?: (state: MapState) => void;
/**
* This event is triggered when the map is about to start loading a new map style.
*/
onWillStartLoadingMap?: () => void;
/**
* This is triggered when the map has successfully loaded a new map style.
*/
onDidFinishLoadingMap?: () => void;
/**
* This event is triggered when the map has failed to load a new map style. On v10 it's deprecated and replaced by onMapLoadingError
* @deprecated use onMapLoadingError
*/
onDidFailLoadingMap?: () => void;
/**
* This event is tiggered when there is an error during map load. V10 only, replaces onDidFailLoadingMap, might be called multiple times and not exclusive with onDidFinishLoadingMap.
*/
onMapLoadingError?: () => void;
/**
* This event is triggered when the map will start rendering a frame.
*/
onWillStartRenderingFrame?: () => void;
/**
* This event is triggered when the map finished rendering a frame.
*/
onDidFinishRenderingFrame?: () => void;
/**
* This event is triggered when the map fully finished rendering a frame.
*/
onDidFinishRenderingFrameFully?: () => void;
/**
* This event is triggered when the map will start rendering the map.
*/
onWillStartRenderingMap?: () => void;
/**
* This event is triggered when the map finished rendering the map.
*/
onDidFinishRenderingMap?: () => void;
/**
* This event is triggered when the map fully finished rendering the map.
*/
onDidFinishRenderingMapFully?: () => void;
/**
* This event is triggered when the user location is updated.
*/
onUserLocationUpdate?: (feature: Location) => void;
/**
* This event is triggered when a style has finished loading.
*/
onDidFinishLoadingStyle?: () => void;
/**
* The emitted frequency of regionwillchange events
*/
regionWillChangeDebounceTime?: number;
/**
* The emitted frequency of regiondidchange events
*/
regionDidChangeDebounceTime?: number;
/**
* Set to true to deselect any selected annotation when the map is tapped. If set to true you will not receive
* the onPress event for the taps that deselect the annotation. Default is false.
*/
deselectAnnotationOnTap?: boolean;
/**
* @private Experimental support for custom MapView instances
*/
mapViewImpl?: string;
/**
* @private Experimental support for custom MapView instances
*/
_nativeImpl?: NativeMapViewActual;
};
const CallbablePropKeys = [
'onRegionWillChange',
'onRegionIsChanging',
'onRegionDidChange',
'onUserLocationUpdate',
'onWillStartLoadingMap',
'onMapLoadingError',
'onDidFinishLoadingMap',
'onDidFailLoadingMap',
'onWillStartRenderingFrame',
'onDidFinishRenderingFrame',
'onDidFinishRenderingFrameFully',
'onWillStartRenderingMap',
'onDidFinishRenderingMap',
'onDidFinishRenderingMapFully',
'onDidFinishLoadingStyle',
'onMapIdle',
'onCameraChanged',
] as const;
type CallbablePropKeys = (typeof CallbablePropKeys)[number];
type CallbablePropKeysWithoutOn = CallbablePropKeys extends `on${infer C}`
? C
: never;
type Debounced<F> = F & { clear(): void; flush(): void };
/**
* MapView backed by Mapbox Native GL
*/
class MapView extends NativeBridgeComponent(
React.PureComponent<Props>,
NativeMapViewModule,
) {
static defaultProps: Props = {
scrollEnabled: true,
pitchEnabled: true,
rotateEnabled: true,
attributionEnabled: true,
compassEnabled: false,
compassFadeWhenNorth: false,
logoEnabled: true,
scaleBarEnabled: true,
surfaceView: RNMBXModule.MapboxV10 ? true : false,
requestDisallowInterceptTouchEvent: false,
regionWillChangeDebounceTime: 10,
regionDidChangeDebounceTime: 500,
};
deprecationLogged: {
contentInset: boolean;
regionDidChange: boolean;
regionIsChanging: boolean;
} = {
contentInset: false,
regionDidChange: false,
regionIsChanging: false,
};
logger: Logger;
_onDebouncedRegionWillChange: Debounced<
(
payload: GeoJSON.Feature<
GeoJSON.Point,
RegionPayload & { isAnimatingFromUserInteraction: boolean }
>,
) => void
>;
_onDebouncedRegionDidChange: Debounced<
(
payload: GeoJSON.Feature<
GeoJSON.Point,
RegionPayload & { isAnimatingFromUserInteraction: boolean }
>,
) => void
>;
_nativeRef?: RNMBXMapViewRefType;
state: {
isReady: boolean | null;
region: null;
width: number;
height: number;
isUserInteraction: boolean;
};
constructor(props: Props) {
super(props);
this.logger = Logger.sharedInstance();
this.logger.start();
this.state = {
isReady: null,
region: null,
width: 0,
height: 0,
isUserInteraction: false,
};
this._onPress = this._onPress.bind(this);
this._onLongPress = this._onLongPress.bind(this);
this._onChange = this._onChange.bind(this);
this._onLayout = this._onLayout.bind(this);
this._onCameraChanged = this._onCameraChanged.bind(this);
// debounced map change methods
this._onDebouncedRegionWillChange = debounce(
this._onRegionWillChange.bind(this),
props.regionWillChangeDebounceTime,
{ immediate: true },
);
this._onDebouncedRegionDidChange = debounce(
this._onRegionDidChange.bind(this),
props.regionDidChangeDebounceTime,
);
}
componentDidMount() {
this._setHandledMapChangedEvents(this.props);
}
componentWillUnmount() {
this._onDebouncedRegionWillChange.clear();
this._onDebouncedRegionDidChange.clear();
this.logger.stop();
}
componentDidUpdate(prevProps: Props) {
const callbackProps = CallbablePropKeys;
const hasCallbackPropsChanged = callbackProps.some(
(propName) => prevProps[propName] !== this.props[propName],
);
if (hasCallbackPropsChanged) {
this._setHandledMapChangedEvents(this.props);
}
}
_setHandledMapChangedEvents(props: Props) {
if (isAndroid() || RNMBXModule.MapboxV10) {
const events: string[] = [];
function addIfHasHandler(name: CallbablePropKeysWithoutOn) {
if (props[`on${name}`] != null) {
if (EventTypes[name] == null) {
if (name === 'DidFailLoadingMap') {
console.warn(
`rnmapbox maps: on${name} is deprecated, please use onMapLoadingError`,
);
} else {
console.warn(`rnmapbox maps: ${name} is not supported`);
}
} else {
events.push(EventTypes[name]);
return true;
}
}
return false;
}
addIfHasHandler('RegionWillChange');
addIfHasHandler('RegionIsChanging');
addIfHasHandler('RegionDidChange');
addIfHasHandler('UserLocationUpdate');
addIfHasHandler('WillStartLoadingMap');
addIfHasHandler('DidFinishLoadingMap');
addIfHasHandler('MapLoadingError');
addIfHasHandler('DidFailLoadingMap');
addIfHasHandler('WillStartRenderingFrame');
addIfHasHandler('DidFinishRenderingFrame');
addIfHasHandler('DidFinishRenderingFrameFully');
addIfHasHandler('WillStartRenderingMap');
addIfHasHandler('DidFinishRenderingMap');
addIfHasHandler('DidFinishRenderingMapFully');
addIfHasHandler('DidFinishLoadingStyle');
addIfHasHandler('CameraChanged');
addIfHasHandler('MapIdle');
if (addIfHasHandler('RegionDidChange')) {
if (!this.deprecationLogged.regionDidChange) {
console.warn(
'onRegionDidChange is deprecated and will be removed in next release - please use onMapIdle. https://github.com/rnmapbox/maps/wiki/Deprecated-RegionIsDidChange',
);
this.deprecationLogged.regionDidChange = true;
}
if (props.onMapIdle) {
console.warn(
'rnmapbox/maps: only one of MapView.onRegionDidChange or onMapIdle is supported',
);
}
}
if (addIfHasHandler('RegionIsChanging')) {
if (!this.deprecationLogged.regionIsChanging) {
console.warn(
'onRegionIsChanging is deprecated and will be removed in next release - please use onCameraChanged. https://github.com/rnmapbox/maps/wiki/Deprecated-RegionIsDidChange',
);
this.deprecationLogged.regionIsChanging = true;
}
if (props.onCameraChanged) {
console.warn(
'rnmapbox/maps: only one of MapView.onRegionIsChanging or onCameraChanged is supported',
);
}
}
if (props.onRegionWillChange) {
console.warn(
'onRegionWillChange is deprecated and will be removed in v10 - please use onRegionIsChanging',
);
}
this._runNativeMethod('setHandledMapChangedEvents', this._nativeRef, [
events,
]);
}
}
/**
* Converts a geographic coordinate to a point in the given view’s coordinate system.
*
* @example
* const pointInView = await this._map.getPointInView([-37.817070, 144.949901]);
*
* @param {Array<number>} coordinate - A point expressed in the map view's coordinate system.
* @return {Array}
*/
async getPointInView(coordinate: Position): Promise<Position> {
const res = await this._runNative<{ pointInView: Position }>(
'getPointInView',
[coordinate],
);
return res.pointInView;
}
/**
* Converts a point in the given view’s coordinate system to a geographic coordinate.
*
* @example
* const coordinate = await this._map.getCoordinateFromView([100, 100]);
*
* @param {Array<number>} point - A point expressed in the given view’s coordinate system.
* @return {Array}
*/
async getCoordinateFromView(point: Position): Promise<Position> {
const res = await this._runNative<{ coordinateFromView: Position }>(
'getCoordinateFromView',
[point],
);
return res.coordinateFromView;
}
/**
* The coordinate bounds (ne, sw) visible in the user’s viewport.
*
* @example
* const visibleBounds = await this._map.getVisibleBounds();
*
* @return {Array}
*/
async getVisibleBounds(): Promise<[Position, Position]> {
const res = await this._runNative<{ visibleBounds: [Position, Position] }>(
'getVisibleBounds',
);
return res.visibleBounds;
}
/**
* Returns an array of rendered map features that intersect with a given point.
*
* @example
* this._map.queryRenderedFeaturesAtPoint([30, 40], ['==', 'type', 'Point'], ['id1', 'id2'])
*
* @param {Array<Number>} coordinate - A point expressed in the map view’s coordinate system.
* @param {Array=} filter - A set of strings that correspond to the names of layers defined in the current style. Only the features contained in these layers are included in the returned array.
* @param {Array=} layerIDs - A array of layer id's to filter the features by
* @return {FeatureCollection}
*/
async queryRenderedFeaturesAtPoint(
coordinate: Position,
filter: FilterExpression | [] = [],
layerIDs: string[] = [],
): Promise<GeoJSON.FeatureCollection | undefined> {
if (!coordinate || coordinate.length < 2) {
throw new Error('Must pass in valid coordinate[lng, lat]');
}
const res = await this._runNative<{ data: GeoJSON.FeatureCollection }>(
'queryRenderedFeaturesAtPoint',
[coordinate, getFilter(filter), layerIDs],
);
if (isAndroid()) {
return JSON.parse(res.data as unknown as string);
}
return res.data as GeoJSON.FeatureCollection;
}
/**
* Returns an array of rendered map features that intersect with the given rectangle,
* restricted to the given style layers and filtered by the given predicate. In v10,
* passing an empty array will query the entire visible bounds of the map.
*
* @example
* this._map.queryRenderedFeaturesInRect([30, 40, 20, 10], ['==', 'type', 'Point'], ['id1', 'id2'])
*
* @param {Array<Number>} bbox - A rectangle expressed in the map view’s coordinate system, density independent pixels and not map coordinates. This can be an empty array to query the visible map area.
* @param {Array=} filter - A set of strings that correspond to the names of layers defined in the current style. Only the features contained in these layers are included in the returned array.
* @param {Array=} layerIDs - A array of layer id's to filter the features by
* @return {FeatureCollection}
*/
async queryRenderedFeaturesInRect(
bbox: BBox | [],
filter: FilterExpression | [] = [],
layerIDs: string[] | null = null,
): Promise<GeoJSON.FeatureCollection | undefined> {
if (
bbox != null &&
(bbox.length === 4 || (RNMBXModule.MapboxV10 && bbox.length === 0))
) {
const res = await this._runNative<{ data: GeoJSON.FeatureCollection }>(
'queryRenderedFeaturesInRect',
[bbox, getFilter(filter), layerIDs],
);
if (isAndroid()) {
return JSON.parse(res.data as unknown as string);
}
return res.data;
} else {
throw new Error(
'Must pass in a valid bounding box: [top, right, bottom, left]. An empty array [] is also acceptable in v10.',
);
}
}
/**
* Returns an array of GeoJSON Feature objects representing features within the specified vector tile or GeoJSON source that satisfy the query parameters.
*
* @example
* this._map.querySourceFeatures('your-source-id', [], ['your-source-layer'])
*
* @param {String} sourceId - Style source identifier used to query for source features.
* @param {Array=} filter - A filter to limit query results.
* @param {Array=} sourceLayerIDs - The name of the source layers to query. For vector tile sources, this parameter is required. For GeoJSON sources, it is ignored.
* @return {FeatureCollection}
*/
async querySourceFeatures(
sourceId: string,
filter: FilterExpression | [] = [],
sourceLayerIDs: string[] = [],
): Promise<GeoJSON.FeatureCollection> {
const args = [sourceId, getFilter(filter), sourceLayerIDs];
const res = await this._runNative<{ data: GeoJSON.FeatureCollection }>(
'querySourceFeatures',
args,
);
if (isAndroid()) {
return JSON.parse(res.data as unknown as string);
}
return res.data;
}
/**
* Map camera will perform updates based on provided config. Deprecated use Camera#setCamera.
* @deprecated use Camera#setCamera
*/
setCamera() {
console.warn(
'MapView.setCamera is deprecated - please use Camera#setCamera',
);
}
_runNative<ReturnType>(
methodName: string,
args: NativeArg[] = [],
): Promise<ReturnType> {
return super._runNativeMethod<typeof RNMBXMapView, ReturnType>(
methodName,
// @ts-ignore TODO: fix types
this._nativeRef as HostComponent<NativeProps> | undefined,
args,
);
}
/**
* Takes snapshot of map with current tiles and returns a URI to the image
* @param {Boolean} writeToDisk If true will create a temp file, otherwise it is in base64
* @return {String}
*/
async takeSnap(writeToDisk = false): Promise<string> {
const res = await this._runNative<{ uri: string }>('takeSnap', [
writeToDisk,
]);
return res.uri;
}
/**
* Returns the current zoom of the map view.
*
* @example
* const zoom = await this._map.getZoom();
*
* @return {Number}
*/
async getZoom(): Promise<number> {
const res = await this._runNative<{ zoom: number }>('getZoom');
return res.zoom;
}
/**
* Returns the map's geographical centerpoint
*
* @example
* const center = await this._map.getCenter();
*
* @return {Array<Number>} Coordinates
*/
async getCenter(): Promise<Position> {
const res = await this._runNative<{ center: Position }>('getCenter');
return res.center;
}
/**
*
* Clears temporary map data from the data path defined in the given resource
* options. Useful to reduce the disk usage or in case the disk cache contains
* invalid data.
*
* v10 only
*/
async clearData(): Promise<void> {
if (!RNMBXModule.MapboxV10) {
console.warn(
'RNMapbox: clearData is only implemented in v10 implementation or later',
);
return;
}
await this._runNative<void>('clearData');
}
/**
* Queries the currently loaded data for elevation at a geographical location.
* The elevation is returned in meters relative to mean sea-level.
* Returns null if terrain is disabled or if terrain data for the location hasn't been loaded yet.
*
* @param {Array<Number>} coordinate - the coordinates to query elevation at
* @return {Number}
*/
async queryTerrainElevation(coordinate: Position): Promise<number> {
const res = await this._runNative<{ data: number }>(
'queryTerrainElevation',
[coordinate],
);
return res.data;
}
/**
* Sets the visibility of all the layers referencing the specified `sourceLayerId` and/or `sourceId`
*
* @example
* await this._map.setSourceVisibility(false, 'composite', 'building')
*
* @param {boolean} visible - Visibility of the layers
* @param {String} sourceId - Identifier of the target source (e.g. 'composite')
* @param {String=} sourceLayerId - Identifier of the target source-layer (e.g. 'building')
*/
setSourceVisibility(
visible: boolean,
sourceId: string,
sourceLayerId: string | null = null,
) {
this._runNative<void>('setSourceVisibility', [
visible,
sourceId,
sourceLayerId,
]);
}
/**
* Updates the state map of a feature within a style source.
*
* Updates entries in the state map of a given feature within a style source.
* Only entries listed in the `state` will be updated.
* An entry in the feature state map that is not listed in `state` will retain its previous value.
*
* @param {string} featureId Identifier of the feature whose state should be updated.
* @param {[k: string]: NativeArg} state Map of entries to update with their respective new values.
* @param {string} sourceId Style source identifier.
* @param {string | null} sourceLayerId Style source layer identifier (for multi-layer sources such as vector sources).
*/
async setFeatureState(
featureId: string,
state: { [k: string]: NativeArg },
sourceId: string,
sourceLayerId: string | null = null,
): Promise<void> {
if (!RNMBXModule.MapboxV10) {
console.warn(
'RNMapbox: setFeatureState is only implemented in v10 implementation or later',
);
return;
}
await this._runNative<void>('setFeatureState', [
featureId,
state,
sourceId,
sourceLayerId,
]);
}
/**
* Returns the state map of a feature within a style source.
*
* @param {string} featureId Identifier of the feature whose state should be queried.
* @param {string} sourceId Style source identifier.
* @param {string | null} sourceLayerId Style source layer identifier (for multi-layer sources such as vector sources).
*/
async getFeatureState(
featureId: string,
sourceId: string,
sourceLayerId: string | null = null,
): Promise<Readonly<Record<string, unknown>>> {
if (!RNMBXModule.MapboxV10) {
console.warn(
'RNMapbox: setFeatureState is only implemented in v10 implementation or later',
);
return {};
}
const res = await this._runNative<{
featureState: Readonly<Record<string, unknown>>;