Created
January 29, 2021 09:13
-
-
Save jittuu/5c0217760d527f7349192c7e3e2858f2 to your computer and use it in GitHub Desktop.
React Native Map
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { isEqual } from 'lodash'; | |
import React from 'react'; | |
import { Dimensions, StyleSheet, ViewStyle } from 'react-native'; | |
import MapView, { LatLng, MapViewProps, Marker, PROVIDER_GOOGLE } from 'react-native-maps'; | |
interface P extends MapViewProps { | |
coordinate?: LatLng; | |
onChange?: (coordinate: LatLng) => void; | |
} | |
const { width } = Dimensions.get('window'); | |
const ASPECT_RATIO = width / (width * (54 / 86)); | |
const LATITUDE = 16.798637; | |
const LONGITUDE = 96.149646; | |
const LATITUDE_DELTA = 0.015; | |
const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO; | |
const initialRegion = { | |
latitude: LATITUDE, | |
longitude: LONGITUDE, | |
latitudeDelta: LATITUDE_DELTA, | |
longitudeDelta: LONGITUDE_DELTA, | |
}; | |
export default class extends React.Component<P> { | |
map: MapView | null; | |
constructor(props: P) { | |
super(props); | |
this.map = null; | |
} | |
componentWillReceiveProps(nextProps: P) { | |
if (!isEqual(nextProps.coordinate, this.props.coordinate)) { | |
if (this.map && nextProps.coordinate) { | |
this.map.animateCamera({ center: nextProps.coordinate }, { duration: 1000 }); | |
} | |
} | |
} | |
handleDragEnd = (e: any) => { | |
const { onChange } = this.props; | |
if (onChange) { | |
onChange(e.nativeEvent.coordinate); | |
} | |
} | |
handleMapLongPress = (e: any) => { | |
const { onChange } = this.props; | |
if (onChange) { | |
onChange(e.nativeEvent.coordinate); | |
} | |
} | |
render() { | |
const { coordinate } = this.props; | |
const marker = coordinate ? ( | |
<Marker | |
draggable={true} | |
coordinate={coordinate} | |
onDragEnd={this.handleDragEnd} | |
/> | |
) : null; | |
return ( | |
<MapView | |
ref={m => this.map = m} | |
zoomEnabled={true} | |
initialRegion={initialRegion} | |
style={styles.container} | |
provider={PROVIDER_GOOGLE} | |
onLongPress={this.handleMapLongPress} | |
> | |
{marker} | |
</MapView> | |
); | |
} | |
} | |
const styles = StyleSheet.create({ | |
container: { | |
width: '100%', | |
height: width * (54 / 86), | |
} as ViewStyle, | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment