I am using react native maps and geolocation. I have set my Latitude and Longitude to
const LATITUDE = 37.78825;
const LONGITUDE = -122.4324
when my application Launches and this.watchlocation function called. Latitude and Longitude changes to my current position and so a componentDidupdate works and message is sent to pubnub..But when I travel some distance. component Did update not called ..how much distance I suppose to travel to send a message again to PubNub. I am using expo ~37.0.3 and "react-native-maps": "0.27.1"
- Here is the sample code to do so
MAP.js
import MapView, { Marker, AnimatedRegion } from 'react-native-maps';
import PubNub from "pubnub";
const { width, height } = Dimensions.get('window');
const ASPECT_RATIO = width / height;
const LATITUDE = 37.78825;
const LONGITUDE = -122.4324;
const LATITUDE_DELTA = 0.0922;
const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO;
const pubnub = new PubNub({
subscribeKey: "demo",
publishKey: "demo",
uuid: "myUUIDv"
});
export default class Trackee extends React.Component {
constructor(props) {
super(props);
this.state = {
latitude: LATITUDE,
longitude: LONGITUDE,
coordinate: new AnimatedRegion({
latitude: LATITUDE,
longitude: LONGITUDE,
latitudeDelta: 0,
longitudeDelta: 0,
}),
};
}
componentDidMount() {
this.watchLocation();
}
componentDidUpdate(prevProps, prevState) {
if (this.state.latitude !== prevState.latitude) {
pubnub.publish({
message: {
latitude: this.state.latitude,
longitude: this.state.longitude,
},
channel: 'location',
});
}
}
componentWillUnmount() {
navigator.geolocation.clearWatch(this.watchID);
}
watchLocation = () => {
const { coordinate } = this.state;
this.watchID = navigator.geolocation.watchPosition(
position => {
const { latitude, longitude } = position.coords;
const newCoordinate = {
latitude,
longitude,
};
if (Platform.OS === 'android') {
if (this.marker) {
coordinate.timing(newCoordinate).start(); // 500 is the duration to animate the marker
}
} else {
coordinate.timing(newCoordinate).start();
}
this.setState({
latitude,
longitude,
});
},
error => console.log(error),
{
enableHighAccuracy: true,
timeout: 20000,
maximumAge: 1000,
distanceFilter: 0,
}
);
};
getMapRegion = () => ({
latitude: this.state.latitude,
longitude: this.state.longitude,
latitudeDelta: LATITUDE_DELTA,
longitudeDelta: LONGITUDE_DELTA,
});
render() {
return (
<SafeAreaView style={{ flex: 1 }}>
<View style={styles.container}>
<MapView style={styles.map} showUserLocation followUserLocation loadingEnabled region={this.getMapRegion()}>
<Marker.Animated
ref={marker => {
this.marker = marker;
}}
coordinate={this.state.coordinate}
/>
</MapView>
</View>
</SafeAreaView>
);
}
}
const styles = StyleSheet.create({
container: {
...StyleSheet.absoluteFillObject,
justifyContent: 'flex-end',
alignItems: 'center',
},
map: {
...StyleSheet.absoluteFillObject,
},
});