Advertisement
Guest User

Untitled

a guest
Mar 19th, 2019
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. componentDidMount() {
  2. this.getCurrentLocation(); // Get users current location
  3. }
  4.  
  5. componentDidUpdate(prevProps, prevState) {
  6. // If prevState changes
  7. if (prevState.newLatitude !== this.state.newLatitude) {
  8. // calculate the distance between initial and new coordinates
  9. this.getDistance();
  10. }
  11. }
  12.  
  13. componentWillUnmount() {
  14. // Remember to clear all listeners
  15. navigator.geolocation.clearWatch(this.watchUserUserPosition());
  16. }
  17.  
  18. getLocation() {
  19. navigator.geolocation.getCurrentPosition((position) => {
  20. this.setState({
  21. latitude: position.coords.latitude,
  22. longitude: position.coords.longitude
  23. }, () => {
  24. this.sendToFirebase();
  25. this.watchUserPosition(); //continue listening for location changes
  26. });
  27. },
  28. (error) => {
  29. //Handle error
  30. },
  31. { enableHighAccuracy: false, timeout: 200000, maximumAge: 1000 },
  32. );
  33. }
  34.  
  35. watchUserPosition() {
  36. navigator.geolocation.watchPosition(
  37. (position) => {
  38. this.setState({
  39. newLatitude: position.coords.latitude,
  40. newLongitude: position.coords.longitude,
  41. error: null,
  42. });
  43. },
  44. (error) => this.setState({ error: error.message }),
  45. { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000, distanceFilter: 10 },
  46. );
  47. }
  48.  
  49. getDistance() {
  50. let initial = {latitude: this.state.latitude, longitude: this.state.longitude};
  51. let newCoord = {latitude: this.state.newLatitude, longitude: this.state.newLongitude};
  52. const distance = geolib.getDistance(initial, newCoord);
  53. if (distance >== 100) {
  54. Alert.alert("Success!", "You have reached 100meters!");
  55. this.sendToFirebase(); // whatever you are saving to firebase
  56. }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement