forked from nitaliano/react-native-mapbox-gl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
474 lines (422 loc) · 14.8 KB
/
index.js
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
'use strict';
import React, { Component, PropTypes } from 'react';
import {
View,
NativeModules,
NativeAppEventEmitter,
requireNativeComponent,
findNodeHandle,
Platform
} from 'react-native';
import cloneDeep from 'lodash/cloneDeep';
import clone from 'lodash/clone';
import isEqual from 'lodash/isEqual';
import Annotation from './Annotation';
const { MapboxGLManager } = NativeModules;
const { mapStyles, userTrackingMode, userLocationVerticalAlignment, unknownResourceCount } = MapboxGLManager;
// Deprecation
function deprecated(obj, key) {
const value = obj[key];
let warned = false;
Object.defineProperty(obj, key, {
get() {
if (!warned) {
console.warn(`${key} is deprecated`); // eslint-disable-line
warned = true;
}
return value;
}
});
}
deprecated(mapStyles, 'emerald');
// Monkeypatch Android commands
if (Platform.OS === 'android') {
const RCTUIManager = NativeModules.UIManager;
const commands = RCTUIManager.RCTMapboxGL.Commands;
// Since we cannot pass functions to dispatchViewManagerCommand, we keep a
// map of callbacks and send an int instead
const callbackMap = new Map();
let nextCallbackId = 0;
Object.keys(commands).forEach(command => {
MapboxGLManager[command] = (handle, ...rawArgs) => {
const args = rawArgs.map(arg => {
if (typeof arg === 'function') {
callbackMap.set(nextCallbackId, arg);
return nextCallbackId++;
}
return arg;
});
RCTUIManager.dispatchViewManagerCommand(handle, commands[command], args);
};
});
NativeAppEventEmitter.addListener('MapboxAndroidCallback', ([ callbackId, args ]) => {
const callback = callbackMap.get(callbackId);
if (!callback) {
throw new Error(`Native is calling a callbackId ${callbackId}, which is not registered`);
}
callbackMap.delete(callbackId);
callback.apply(null, args);
});
}
// Metrics
let _metricsEnabled = MapboxGLManager.metricsEnabled;
function setMetricsEnabled(enabled: boolean) {
_metricsEnabled = enabled;
MapboxGLManager.setMetricsEnabled(enabled);
}
function getMetricsEnabled() {
return _metricsEnabled;
}
// Access token
function setAccessToken(token: string) {
MapboxGLManager.setAccessToken(token);
}
// Offline
function bindCallbackToPromise(callback, promise) {
if (callback) {
promise.then(value => {
callback(null, value);
}).catch(err => {
callback(err);
})
}
}
function addOfflinePack(options, callback) {
let _options = options;
// Workaround the fact that RN Android can't serialize JSON correctly
if (Platform.OS === 'android') {
_options = {
...options,
metadata: JSON.stringify({ v: options.metadata })
};
}
const promise = MapboxGLManager.addOfflinePack(_options);
bindCallbackToPromise(callback, promise);
return promise;
}
function getOfflinePacks(callback) {
let promise = MapboxGLManager.getOfflinePacks();
if (Platform.OS === 'android') {
promise = promise.then(packs => {
packs.forEach(progress => {
if (progress.metadata) {
progress.metadata = JSON.parse(progress.metadata).v;
}
});
return packs;
});
}
bindCallbackToPromise(callback, promise);
return promise;
}
function removeOfflinePack(packName, callback) {
const promise = MapboxGLManager.removeOfflinePack(packName);
bindCallbackToPromise(callback, promise);
return promise;
}
function setOfflinePackProgressThrottleInterval(milis) {
MapboxGLManager.setOfflinePackProgressThrottleInterval(milis);
}
function addOfflinePackProgressListener(handler) {
let _handler = handler;
if (Platform.OS === 'android') {
_handler = (progress) => {
if (progress.metadata) {
progress.metadata = JSON.parse(progress.metadata).v;
}
handler(progress);
};
}
return NativeAppEventEmitter.addListener('MapboxOfflineProgressDidChange', _handler);
}
function addOfflineMaxAllowedTilesListener(handler) {
return NativeAppEventEmitter.addListener('MapboxOfflineMaxAllowedTiles', handler);
}
function addOfflineErrorListener(handler) {
return NativeAppEventEmitter.addListener('MapboxOfflineError', handler);
}
class MapView extends Component {
constructor(props) {
super(props);
this._onRegionDidChange = this._onRegionDidChange.bind(this);
this._onRegionWillChange = this._onRegionWillChange.bind(this);
this._onOpenAnnotation = this._onOpenAnnotation.bind(this);
this._onCloseAnnotation = this._onCloseAnnotation.bind(this);
this._onRightAnnotationTapped = this._onRightAnnotationTapped.bind(this);
this._onChangeUserTrackingMode = this._onChangeUserTrackingMode.bind(this);
this._onUpdateUserLocation = this._onUpdateUserLocation.bind(this);
this._onLongPress = this._onLongPress.bind(this);
this._onTap = this._onTap.bind(this);
this._onFinishLoadingMap = this._onFinishLoadingMap.bind(this);
this._onStartLoadingMap = this._onStartLoadingMap.bind(this);
this._onLocateUserFailed = this._onLocateUserFailed.bind(this);
this._onNativeComponentMount = this._onNativeComponentMount.bind(this);
}
// Viewport setters
setDirection(direction, animated = true, callback) {
return this.easeTo({ direction }, animated, callback);
}
setZoomLevel(zoomLevel, animated = true, callback) {
return this.easeTo({ zoomLevel }, animated, callback);
}
setCenterCoordinate(latitude, longitude, animated = true, callback) {
return this.easeTo({ latitude, longitude }, animated, callback);
}
setCenterCoordinateZoomLevel(latitude, longitude, zoomLevel, animated = true, callback) {
return this.easeTo({ latitude, longitude, zoomLevel }, animated, callback);
}
setCenterCoordinateZoomLevelPitch(latitude, longitude, zoomLevel, pitch, animated = true, callback) {
return this.easeTo({ latitude, longitude, zoomLevel, pitch }, animated, callback);
}
setPitch(pitch, animated = true, callback) {
return this.easeTo({ pitch }, animated, callback);
}
easeTo(options, animated = true, callback) {
let _resolve;
const promise = new Promise(resolve => _resolve = resolve);
MapboxGLManager.easeTo(findNodeHandle(this), options, animated, () => {
callback && callback();
_resolve();
});
return promise;
}
setVisibleCoordinateBounds(latitudeSW, longitudeSW, latitudeNE, longitudeNE, paddingTop = 0, paddingRight = 0, paddingBottom = 0, paddingLeft = 0, animated = true) {
MapboxGLManager.setVisibleCoordinateBounds(findNodeHandle(this), latitudeSW, longitudeSW, latitudeNE, longitudeNE, paddingTop, paddingRight, paddingBottom, paddingLeft, animated);
}
// Getters
getCenterCoordinateZoomLevel(callback) {
MapboxGLManager.getCenterCoordinateZoomLevel(findNodeHandle(this), callback);
}
getDirection(callback) {
MapboxGLManager.getDirection(findNodeHandle(this), callback);
}
getBounds(callback) {
MapboxGLManager.getBounds(findNodeHandle(this), callback);
}
getPitch(callback) {
MapboxGLManager.getPitch(findNodeHandle(this), callback);
}
// Others
selectAnnotation(annotationId, animated = true) {
MapboxGLManager.selectAnnotation(findNodeHandle(this), annotationId, animated);
}
deselectAnnotation() {
MapboxGLManager.deselectAnnotation(findNodeHandle(this));
}
queryRenderedFeatures(options, callback) {
let promise;
if (Platform.OS === 'android') {
promise = Promise.reject('queryRenderedFeatures() is not yet implemented on Android');
} else {
promise = MapboxGLManager.queryRenderedFeatures(findNodeHandle(this), options);
}
bindCallbackToPromise(callback, promise);
return promise;
}
// Events
_onRegionDidChange(event: Event) {
if (this.props.onRegionDidChange) this.props.onRegionDidChange(event.nativeEvent.src);
}
_onRegionWillChange(event: Event) {
if (this.props.onRegionWillChange) this.props.onRegionWillChange(event.nativeEvent.src);
}
_onOpenAnnotation(event: Event) {
if (this.props.onOpenAnnotation) this.props.onOpenAnnotation(event.nativeEvent.src);
}
_onCloseAnnotation(event: Event) {
if (this.props.onCloseAnnotation) this.props.onCloseAnnotation(event.nativeEvent.src);
}
_onRightAnnotationTapped(event: Event) {
if (this.props.onRightAnnotationTapped) this.props.onRightAnnotationTapped(event.nativeEvent.src);
}
_onChangeUserTrackingMode(event: Event) {
if (this.props.onChangeUserTrackingMode) this.props.onChangeUserTrackingMode(event.nativeEvent.src);
}
_onUpdateUserLocation(event: Event) {
if (this.props.onUpdateUserLocation) this.props.onUpdateUserLocation(event.nativeEvent.src);
}
_onLongPress(event: Event) {
if (this.props.onLongPress) this.props.onLongPress(event.nativeEvent.src);
}
_onTap(event: Event) {
if (this.props.onTap) this.props.onTap(event.nativeEvent.src);
}
_onFinishLoadingMap(event: Event) {
if (this.props.onFinishLoadingMap) this.props.onFinishLoadingMap(event.nativeEvent.src);
}
_onStartLoadingMap(event: Event) {
if (this.props.onStartLoadingMap) this.props.onStartLoadingMap(event.nativeEvent.src);
}
_onLocateUserFailed(event: Event) {
if (this.props.onLocateUserFailed) this.props.onLocateUserFailed(event.nativeEvent.src);
}
static propTypes = {
...View.propTypes,
initialZoomLevel: PropTypes.number,
initialDirection: PropTypes.number,
initialCenterCoordinate: PropTypes.shape({
latitude: PropTypes.number.isRequired,
longitude: PropTypes.number.isRequired
}),
clipsToBounds: PropTypes.bool,
debugActive: PropTypes.bool,
rotateEnabled: PropTypes.bool,
scrollEnabled: PropTypes.bool,
zoomEnabled: PropTypes.bool,
minimumZoomLevel: PropTypes.number,
maximumZoomLevel: PropTypes.number,
pitchEnabled: PropTypes.bool,
annotationsPopUpEnabled: PropTypes.bool,
showsUserLocation: PropTypes.bool,
styleURL: PropTypes.string.isRequired,
userTrackingMode: PropTypes.number,
attributionButtonIsHidden: PropTypes.bool,
logoIsHidden: PropTypes.bool,
compassIsHidden: PropTypes.bool,
userLocationVerticalAlignment: PropTypes.number,
contentInset: PropTypes.arrayOf(PropTypes.number),
annotations: PropTypes.arrayOf(PropTypes.shape({
coordinates: PropTypes.array.isRequired,
title: PropTypes.string,
subtitle: PropTypes.string,
fillAlpha: PropTypes.number,
fillColor: PropTypes.string,
strokeAlpha: PropTypes.number,
strokeColor: PropTypes.string,
strokeWidth: PropTypes.number,
id: PropTypes.string,
type: PropTypes.string.isRequired,
rightCalloutAccessory: PropTypes.shape({
height: PropTypes.number,
width: PropTypes.number,
url: PropTypes.string
}),
annotationImage: PropTypes.shape({
height: PropTypes.number,
width: PropTypes.number,
url: PropTypes.string
})
})),
annotationsAreImmutable: PropTypes.bool,
onRegionDidChange: PropTypes.func,
onRegionWillChange: PropTypes.func,
onOpenAnnotation: PropTypes.func,
onCloseAnnotation: PropTypes.func,
onUpdateUserLocation: PropTypes.func,
onRightAnnotationTapped: PropTypes.func,
onFinishLoadingMap: PropTypes.func,
onStartLoadingMap: PropTypes.func,
onLocateUserFailed: PropTypes.func,
onLongPress: PropTypes.func,
onTap: PropTypes.func,
onChangeUserTrackingMode: PropTypes.func,
};
static defaultProps = {
initialCenterCoordinate: {
latitude: 0,
longitude: 0
},
initialDirection: 0,
initialZoomLevel: 0,
minimumZoomLevel: 0,
maximumZoomLevel: 20, // default in native map view
debugActive: false,
rotateEnabled: true,
scrollEnabled: true,
pitchEnabled: true,
showsUserLocation: false,
styleURL: mapStyles.streets,
userTrackingMode: userTrackingMode.none,
zoomEnabled: true,
annotationsPopUpEnabled: true,
attributionButtonIsHidden: false,
logoIsHidden: false,
compassIsHidden: false,
annotationsAreImmutable: false,
annotations: [],
contentInset: [0, 0, 0, 0]
};
componentWillReceiveProps(newProps) {
const oldKeys = clone(this._annotations);
const itemsToAdd = [];
const itemsToRemove = [];
const isImmutable = newProps.annotationsAreImmutable;
if (isImmutable && this.props.annotations === newProps.annotations) {
return;
}
newProps.annotations.forEach(annotation => {
const id = annotation.id;
if (!isEqual(this._annotations[id], annotation)) {
this._annotations[id] = isImmutable ? annotation : cloneDeep(annotation);
itemsToAdd.push(annotation);
}
oldKeys[id] = null;
});
for (let key in oldKeys) {
if (oldKeys[key]) {
delete this._annotations[key];
itemsToRemove.push(key);
}
}
MapboxGLManager.spliceAnnotations(findNodeHandle(this), false, itemsToRemove, itemsToAdd);
}
_native = null;
_onNativeComponentMount(ref) {
if (this._native === ref) { return; }
this._native = ref;
MapboxGLManager.spliceAnnotations(findNodeHandle(this), true, [], this.props.annotations);
const isImmutable = this.props.annotationsAreImmutable;
this._annotations = this.props.annotations.reduce((acc, annotation) => {
acc[annotation.id] = isImmutable ? annotation : cloneDeep(annotation);
return acc;
}, {});
}
setNativeProps(nativeProps) {
this._native && this._native.setNativeProps(nativeProps);
}
componentWillUnmount() {
this._native = null;
}
render() {
return (
<MapboxGLView
{...this.props}
ref={this._onNativeComponentMount}
onRegionDidChange={this._onRegionDidChange}
onRegionWillChange={this._onRegionWillChange}
enableOnRegionDidChange={!!this.props.onRegionDidChange}
enableOnRegionWillChange={!!this.props.onRegionWillChange}
onOpenAnnotation={this._onOpenAnnotation}
onCloseAnnotation={this._onCloseAnnotation}
onRightAnnotationTapped={this._onRightAnnotationTapped}
onUpdateUserLocation={this._onUpdateUserLocation}
onLongPress={this._onLongPress}
onTap={this._onTap}
onFinishLoadingMap={this._onFinishLoadingMap}
onStartLoadingMap={this._onStartLoadingMap}
onLocateUserFailed={this._onLocateUserFailed}
onChangeUserTrackingMode={this._onChangeUserTrackingMode}
/>
);
}
}
const MapboxGLView = requireNativeComponent('RCTMapboxGL', MapView, {
nativeOnly: {
onChange: true,
enableOnRegionDidChange: true,
enableOnRegionWillChange: true
}
});
const Mapbox = {
MapView,
Annotation,
mapStyles, userTrackingMode, userLocationVerticalAlignment, unknownResourceCount,
getMetricsEnabled, setMetricsEnabled,
setAccessToken,
addOfflinePack, getOfflinePacks, removeOfflinePack,
addOfflinePackProgressListener,
addOfflineMaxAllowedTilesListener,
addOfflineErrorListener,
setOfflinePackProgressThrottleInterval
};
module.exports = Mapbox;