forked from reggie3/react-native-webview-leaflet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
WebViewLeaflet.js
580 lines (537 loc) · 16.8 KB
/
WebViewLeaflet.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
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
import React from 'react';
import {
View,
StyleSheet,
ActivityIndicator,
Platform,
Text,
} from 'react-native';
import { WebView } from 'react-native-webview';
import PropTypes from 'prop-types';
// import Button from './Button';
// import AssetUtils from 'expo-asset-utils'
const asset = require('./assets/dist/index.html');
const util = require('util');
const isValidCoordinates = require('is-valid-coordinates');
const uniqby = require('lodash.uniqby');
// look up these issues related to including index.html
// https://github.com/facebook/react-native/issues/8996
// https://github.com/facebook/react-native/issues/16133
/* const INDEX_FILE_PATH = `./assets/dist/index.html`;
const INDEX_FILE_ASSET_URI = Asset.fromModule(require(INDEX_FILE_PATH)).uri;
*/
// const INDEX_FILE = require(INDEX_FILE_PATH);
const MESSAGE_PREFIX = 'react-native-webview-leaflet';
// const requiredAsset = require('./assets/dist/index.html');
export default class WebViewLeaflet extends React.Component {
constructor(props) {
super(props);
this.state = {
mapLoaded: false,
webviewErrorMessages: [],
hasError: false,
hasErrorMessage: '',
hasErrorInfo: '',
asset,
};
}
componentDidCatch(error, info) {
// Display fallback UI
this.setState({
hasError: true,
hasErrorMessage: error,
hasErrorInfo: info,
});
}
componentDidUpdate = (prevProps, prevState) => {
// check that centerPosition prop exists,
// that the current centerPosition does not equal the previous one,
// and that the centerPosition is a valid lat, lng
// if so, send a message to the map to update its current position
if (
this.props.centerPosition &&
this.props.centerPosition.length == 2 &&
prevProps.centerPosition !== this.props.centerPosition
) {
if (
isValidCoordinates(
this.props.centerPosition[1],
this.props.centerPosition[0],
)
) {
this.sendMessage({ centerPosition: this.props.centerPosition });
// store the center position so that we can ensure the map gets it upon
// its loading since it is possible that the position might
// be availible before the map has been loaded
this.setState({ centerPosition: this.props.centerPosition });
} else {
console.warn(
'Invalid coordinates provided to centerPosition: ',
this.props.centerPosition,
);
}
}
// handle updates to own position
if (
this.props.ownPositionMarker &&
this.props.ownPositionMarker.coords &&
this.props.ownPositionMarker.coords.length === 2 &&
JSON.stringify(prevProps.ownPositionMarker) !==
JSON.stringify(this.props.ownPositionMarker)
) {
if (
isValidCoordinates(
this.props.ownPositionMarker.coords[1],
this.props.ownPositionMarker.coords[0],
)
) {
console.log('****** sending position');
// this.sendMessage({ ownPositionMarker: this.props.ownPositionMarker });
// store the center position so that we can ensure the map gets it upon
// its loading since it is possible that the position might
// be availible before the map has been loaded
this.setState({ ownPositionMarker: this.props.ownPositionMarker });
} else {
console.warn(
'Invalid coordinates provided to ownPositionMarker: ',
this.props.ownPositionMarker.coords,
);
}
}
// handle updates to map markers array
if (this.props.markers && prevProps.markers !== this.props.markers) {
// debugger;
let validLocations = this.props.markers.filter(marker => {
if (!marker || !marker.coords || marker.coords.length !== 2)
return false;
return isValidCoordinates(marker.coords[1], marker.coords[0]);
});
this.sendMessage({ locations: validLocations });
// store the center position so that we can ensure the map gets it upon
// its loading since it is possible that the position might
// be availible before the map has been loaded
this.setState({ locations: validLocations });
}
if (
this.props.geometryLayers &&
prevProps.geometryLayers !== this.props.geometryLayers
) {
this.setState({ geometryLayers: this.props.geometryLayers });
}
if (
this.props.useMarkerClustering &&
this.props.useMarkerClustering !== prevProps.useMarkerClustering
) {
this.sendMessage({ useMarkerClustering: this.props.useMarkerClustering });
}
// do the same for using map bounds
if (
this.props.hasOwnProperty('bounds') &&
this.props.bounds !== prevProps.bounds
) {
this.sendMessage({ bounds: this.props.bounds });
}
// do the same for using map boundsOptions
if (
this.props.hasOwnProperty('boundsOptions') &&
this.props.boundsOptions !== prevProps.boundsOptions
) {
this.sendMessage({ boundsOptions: this.props.boundsOptions });
}
// actions to be performed one time immediately after the map
// completes loading
if (!prevState.mapLoaded && this.state.mapLoaded) {
this.doPostMapLoadedActions();
}
};
doPostMapLoadedActions = () => {
// Here is our chance to send stuff to the map once it has loaded
// Create an object that will have the update that the map will
// get once it has loaded
let onMapLoadedUpdate = {
mapLayers: this.props.mapLayers,
};
// Check the state for any items that may have been received prior to
// the map loading, and send them to the map
// check if we have a center position
if (
this.props.centerPosition &&
this.props.centerPosition.length === 2 &&
isValidCoordinates(
this.props.centerPosition[1],
this.props.centerPosition[0],
)
) {
onMapLoadedUpdate = {
...onMapLoadedUpdate,
centerPosition: this.props.centerPosition,
};
}
// do the same for ownPostionMarker
if (
this.props.ownPositionMarker &&
this.props.ownPositionMarker.coords &&
this.props.ownPositionMarker.coords.length == 2 &&
isValidCoordinates(
this.props.ownPositionMarker.coords[1],
this.props.ownPositionMarker.coords[0],
)
) {
onMapLoadedUpdate = {
...onMapLoadedUpdate,
ownPositionMarker: this.props.ownPositionMarker,
};
}
// do the same for map markers
if (this.props.markers) {
let validLocations = this.props.markers.filter(marker => {
if (!marker || !marker.coords || marker.coords.length !== 2)
return false;
return isValidCoordinates(marker.coords[1], marker.coords[0]);
});
onMapLoadedUpdate = {
...onMapLoadedUpdate,
locations: validLocations,
};
}
if (this.props.geometryLayers) {
onMapLoadedUpdate = {
...onMapLoadedUpdate,
geometryLayers: this.props.geometryLayers,
};
}
// do the same for zoom
if (this.props.zoom) {
onMapLoadedUpdate = {
...onMapLoadedUpdate,
zoom: this.props.zoom,
};
}
// do the same for using marker clustering
if (this.props.useMarkerClustering) {
onMapLoadedUpdate = {
...onMapLoadedUpdate,
useMarkerClustering: this.props.useMarkerClustering,
};
}
// do the same for using map bounds
if (this.props.bounds) {
onMapLoadedUpdate = {
...onMapLoadedUpdate,
...{ bounds: this.props.bounds },
};
}
if (this.props.boundsOptions) {
onMapLoadedUpdate = {
...onMapLoadedUpdate,
...{ boundsOptions: this.props.boundsOptions },
};
}
if (Object.keys(onMapLoadedUpdate).length > 0) {
// console.log({ onMapLoadedUpdate });
this.sendMessage(onMapLoadedUpdate);
}
};
// data to send is an object containing key value pairs that will be
// spread into the destination's state
sendMessage = payload => {
if (this.state.mapLoaded) {
// only send message when webview is loaded
const message = JSON.stringify({
prefix: MESSAGE_PREFIX,
payload,
});
// If the user has sent a centering messaging, then store the location
// so that we can refer to it later if the built in centering button
// is pressed
/* if (payload.centerPosition) {
this.setState({ centerPosition: payload.centerPosition });
} */
// console.warn(`WebViewLeaflet: sending message: `, JSON.stringify(message));
this.webview.postMessage(message, '*');
}
};
//
handleMessage = data => {
let msgData;
// console.log({ data });
msgData = JSON.parse(data);
if (msgData.hasOwnProperty('prefix') && msgData.prefix === MESSAGE_PREFIX) {
// console.log(`WebViewLeaflet: received message: `, msgData.payload);
// if we receive an event, then pass it to the parent by calling
// the parent function wtith the same name as the event, and passing
// the entire payload as a parameter
if (
msgData.payload.event &&
this.props.eventReceiver.hasOwnProperty(msgData.payload.event)
) {
this.props.eventReceiver[msgData.payload.event](msgData.payload);
}
// WebViewLeaflet will also need to know of some state changes, such as
// when the mapComponent is mounted
else {
this.props.eventReceiver.setState({
state: {
...this.props.eventReceiver.state,
mapState: {
...this.props.eventReceiver.mapState,
...msgData.payload,
},
},
});
}
}
};
validateLocations = locations => {
// confirm the location coordinates are valid
const validCoordLocations = locations.filter(location => {
return isValidCoordinates(location.coords[1], location.coords[0]);
});
// remove any locations that are already in the component state's "locations"
// create a new array containing all the locations
let combinedArray = [...this.state.locations, ...validCoordLocations];
// remove duplicate locations
const deDupedLocations = uniqby(combinedArray, 'id');
this.sendLocations(deDupedLocations);
this.setState({ locations: deDupedLocations });
};
onError = error => {
this.setState({
webviewErrorMessages: [...this.state.webviewErrorMessages, error],
});
};
renderError = error => {
this.setState({
webviewErrorMessages: [...this.state.webviewErrorMessages, error],
});
};
renderLoadingIndicator = () => {
return (
<View style={styles.activityOverlayStyle}>
<View style={styles.activityIndicatorContainer}>
<ActivityIndicator
size="large"
animating={!this.props.eventReceiver.state.mapsState.mapLoaded}
/>
</View>
</View>
);
};
maybeRenderMap = () => {
if (this.state.asset) {
return (
<View style={{ flex: 1, overflow: 'hidden' }}>
<WebView
style={{
...StyleSheet.absoluteFillObject,
}}
ref={ref => {
this.webview = ref;
}}
/* source={INDEX_FILE} */
source={this.state.asset}
// source={{ uri: 'http://google.com.br' }}
// source={
// Platform.OS === 'ios'
// ? { html: this.state.asset }
// : { uri: this.state.asset.uri }
// }
startInLoadingState={true}
renderLoading={this.renderLoading}
// renderError={error => {
// console.warn(
// 'RENDER ERROR: ',
// util.inspect(error, {
// showHidden: false,
// depth: null,
// }),
// );
// }}
javaScriptEnabled={true}
// onError={error => {
// console.log(
// 'ERROR: ',
// util.inspect(error, {
// showHidden: false,
// depth: null,
// }),
// );
// }}
// /* scalesPageToFit={false} */
mixedContentMode={'always'}
onMessage={event => {
if (event && event.nativeEvent && event.nativeEvent.data) {
this.handleMessage(event.nativeEvent.data);
}
}}
// onLoadStart={() => {}}
onLoadEnd={() => {
if (this.props.eventReceiver.hasOwnProperty('onLoad')) {
this.props.eventReceiver.onLoad();
}
// Set the component state to showw that the map has been loaded.
// This will let us do things during component update once the map
// is loaded.
this.setState({ mapLoaded: true });
}}
domStorageEnabled={true}
useWebKit={true}
/>
</View>
);
}
return <ActivityIndicator />;
};
maybeRenderWebviewError = () => {
if (this.state.webviewErrorMessages.length > 0) {
return (
<View style={{ zIndex: 2000, backgroundColor: 'orange', margin: 4 }}>
{this.state.webviewErrorMessages.map((errorMessage, index) => {
return <Text key={index}>{errorMessage}</Text>;
})}
</View>
);
}
return null;
};
maybeRenderErrorBoundaryMessage = () => {
if (this.state.hasError)
return (
<View style={{ zIndex: 2000, backgroundColor: 'red', margin: 5 }}>
{util.inspect(this.state.webviewErrorMessages, {
showHidden: false,
depth: null,
})}
</View>
);
return null;
};
renderCenterOnOwnPositionMarkerButton = () => {
if (this.props.ownPositionMarker) {
if (
this.props.ownPositionMarker.coords &&
this.props.ownPositionMarker.coords.length == 2 &&
isValidCoordinates(
this.props.ownPositionMarker.coords[1],
this.props.ownPositionMarker.coords[0],
)
) {
return (
<View
style={{
position: 'absolute',
right: 10,
bottom: 20,
padding: 10,
}}
>
{/* <Button
onPress={() => {
this.sendMessage({
centerPosition: this.props.ownPositionMarker.coords,
});
}}
text={'🎯'}
/> */}
</View>
);
}
return null;
} else {
console.log(
"Prop 'ownPositionMarker' must be passed in order to display the center on own position button.",
);
return null;
}
};
render() {
return (
<View
style={{
flex: 1,
}}
>
<View
style={{
...StyleSheet.absoluteFillObject,
backgroundColor: '#fff1ad',
}}
>
{this.maybeRenderMap()}
{this.maybeRenderErrorBoundaryMessage()}
{this.maybeRenderWebviewError()}
{this.props.centerButton
? this.renderCenterOnOwnPositionMarkerButton()
: null}
</View>
</View>
);
}
}
WebViewLeaflet.propTypes = {
defaultIconSize: PropTypes.array,
currentPosition: PropTypes.array,
locations: PropTypes.array,
onMapClicked: PropTypes.func,
onMarkerClicked: PropTypes.func,
onWebviewReady: PropTypes.func,
panToLocation: PropTypes.bool,
zoom: PropTypes.number,
showZoomControls: PropTypes.bool,
centerButton: PropTypes.bool,
showMapAttribution: PropTypes.bool,
currentPositionMarkerStyle: PropTypes.object,
onCurrentPositionClicked: PropTypes.func,
};
WebViewLeaflet.defaultProps = {
defaultIconSize: [36, 36],
zoom: 5,
showZoomControls: true,
centerButton: false,
panToLocation: false,
showMapAttribution: false,
currentPosition: [38.89511, -77.03637],
currentPositionMarkerStyle: {
icon: '❤️',
animation: {
name: 'beat',
duration: 0.25,
delay: 0,
interationCount: 'infinite',
direction: 'alternate',
},
size: [36, 36],
},
useMarkerClustering: false,
};
const styles = StyleSheet.create({
activityOverlayStyle: {
...StyleSheet.absoluteFillObject,
backgroundColor: 'rgba(255, 255, 255, .5)',
display: 'flex',
justifyContent: 'center',
alignContent: 'center',
borderRadius: 5,
},
activityIndicatorContainer: {
backgroundColor: 'lightgray',
padding: 10,
borderRadius: 50,
alignSelf: 'center',
shadowColor: '#000000',
shadowOffset: {
width: 0,
height: 3,
},
shadowRadius: 5,
shadowOpacity: 1.0,
},
button: Platform.select({
ios: {},
android: {
elevation: 4,
backgroundColor: '#2196F3',
borderRadius: 2,
},
}),
});