Geolocation.watchPosition not working in React Native

Viewed 465

I'm using react-native-geolocation-service but I'm having a problem with watchPosition because it wont consistently update (showing the latest position) when I change my location inside the extended control of a virtualized phone.

import * as React from 'react';
import { useState,useEffect } from 'react';
import {
  View,
  TouchableOpacity,
} from 'react-native';
import Geolocation from 'react-native-geolocation-service';


export default function TestScreen () {

  const hasLocationPermission = async () => {
    if (Platform.OS === 'android' && Platform.Version < 23) {
      return true;
    }

    const hasPermission = await PermissionsAndroid.check(
      PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
    );

    if (hasPermission) {
      return true;
    }

    const status = await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
    );

    if (status === PermissionsAndroid.RESULTS.GRANTED) {
      return true;
    }

    if (status === PermissionsAndroid.RESULTS.DENIED) {
      ToastAndroid.show(
        'Location permission denied by user.',
        ToastAndroid.LONG,
      );
    } else if (status === PermissionsAndroid.RESULTS.NEVER_ASK_AGAIN) {
      ToastAndroid.show(
        'Location permission revoked by user.',
        ToastAndroid.LONG,
      );
    }

    return false;
  };
  
  useEffect(() => { 
      let watch = Geolocation.watchPosition((position) => {
        console.log(position);
      });
  });


  const getLocation = async () => {
    const hasPermission = await hasLocationPermission();

    if (!hasPermission) {
      return;
    }

    Geolocation.getCurrentPosition(
      (position) => {
        //setLocation(position);
        console.log(position);
      },
      (error) => {
        Alert.alert(`Code ${error.code}`, error.message);
        //setLocation(null);
        console.log(error);
      },
      {
        accuracy: {
          android: 'high',
          ios: 'best',
        },
        timeout: 15000,
        maximumAge: 10000,
        distanceFilter: 1,
      },
    );
  };


  return (
      <View>
          <TouchableOpacity onPress={ () => getLocation() }>
              <Text>Hello there!</Text>
          </TouchableOpacity>
      </View>
    );
};

My console logs twice the position when I click the TouchableOpacity but when I change the position the console won't show anything.

0 Answers
Related