Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, { useState, useEffect, useCallback } from 'react';
- import { View, Text, Button, PermissionsAndroid, Platform } from 'react-native';
- import Geolocation from 'react-native-geolocation-service';
- const TARGET_LOCATION = { latitude: 28.7041, longitude: 77.1025 };
- const DISTANCE_THRESHOLD = 1000;
- const TIMER_INTERVAL = 300000;
- async function requestLocationPermission() {
- if (Platform.OS !== 'android') return true;
- try {
- const granted = await PermissionsAndroid.request(
- PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
- {
- title: 'Location Permission',
- message: 'This app needs access to your location.',
- buttonNeutral: 'Ask Me Later',
- buttonNegative: 'Cancel',
- buttonPositive: 'OK',
- },
- );
- return granted === PermissionsAndroid.RESULTS.GRANTED;
- } catch (err) {
- console.warn(err);
- return false;
- }
- }
- const Timer = () => {
- const [timerState, setTimerState] = useState('stopped');
- const [timerID, setTimerID] = useState(null);
- const getDistanceFromLatLonInM = useCallback((lat1, lon1, lat2, lon2) => {
- const deg2rad = deg => (deg * Math.PI) / 180;
- const R = 6371e3;
- const dLat = deg2rad(lat2 - lat1);
- const dLon = deg2rad(lon2 - lon1);
- const a =
- Math.sin(dLat / 2) * Math.sin(dLat / 2) +
- Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
- Math.sin(dLon / 2) * Math.sin(dLon / 2);
- const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
- return R * c;
- }, []);
- const checkLocation = useCallback(() => {
- Geolocation.getCurrentPosition(
- position => {
- const { latitude, longitude } = position.coords;
- const distance = getDistanceFromLatLonInM(
- latitude,
- longitude,
- TARGET_LOCATION.latitude,
- TARGET_LOCATION.longitude
- );
- if (distance <= DISTANCE_THRESHOLD && timerState !== 'running') {
- setTimerState('running');
- } else if (distance > DISTANCE_THRESHOLD && timerState !== 'stopped') {
- setTimerState('stopped');
- }
- },
- error => {
- console.error(error.code, error.message);
- },
- { enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 },
- );
- }, [timerState]);
- useEffect(() => {
- let id;
- const createTimer = async () => {
- const hasPermission = await requestLocationPermission();
- if (hasPermission) {
- checkLocation();
- id = setInterval(checkLocation, TIMER_INTERVAL);
- setTimerID(id);
- }
- };
- createTimer();
- return () => {
- if (id) clearInterval(id);
- };
- }, [checkLocation]);
- return (
- <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
- <Text style={{ fontSize: 24, margin: 10 }}>Timer state: {timerState.toUpperCase()}</Text>
- <Button title="Start" onPress={() => setTimerState('running')} />
- <Button title="Stop" onPress={() => setTimerState('stopped')} />
- </View>
- );
- };
- export default Timer;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement