Home > Net >  Updating users location every x amount of seconds
Updating users location every x amount of seconds

Time:01-29

I am trying to log the users location every x amount of seconds. In this specific code, it is 5 seconds. I am using watchPositionAsync. The code below I thought would log the latitude and longitude every 5 seconds however it does not log anything in the console at all.

I want to be sure it is updating and logging it in the console would confirm that. Let me know if you have any questions or need to see more code.

expo-location docs: https://docs.expo.dev/versions/latest/sdk/location/

import * as Location from 'expo-location';

function MyTabs() {

  const [latitude, setLatitude] = React.useState(null);
  const [longitude, setLongitude] = React.useState(null);
  

React.useEffect(() => {
    
    (async () => {
      let { status } = await Location.requestForegroundPermissionsAsync();
      if (status !== 'granted') {
        permissionAlert();
        return;
      }

      let location = await Location.watchPositionAsync({
        accuracy: Location.Accuracy.High,
        timeInterval: 5000,
        distanceInterval: 50
        
      },
        console.log('update location!', location.coords.latitude, location.coords.longitude)
      );
      setLatitude(location.coords.latitude)
      setLongitude(location.coords.longitude);

    })();
  }, []);


CodePudding user response:

the second parameter of watch position suppose to be a callback with the location object as the first arg

Location.watchPositionAsync({
        accuracy: Location.Accuracy.High,
        timeInterval: 5000,
        distanceInterval: 50
        
      },
        location => {
            console.log('update location!', location.coords.latitude, location.coords.longitude)
            setLatitude(location.coords.latitude)
            setLongitude(location.coords.longitude);
      );

CodePudding user response:

You can find some information on the documentation

Note that:

  1. you should pass a callback as the second argument of watchPositionAsync as explained here
  2. timeInterval is Android-only, so if you're testing it on iOS it won't work; moreover, that timeInterval is the minimum time that should pass, it doesn't notify you every 5 seconds, it's more like a throttle (https://css-tricks.com/debouncing-throttling-explained-examples/#aa-throttle);
  3. you set a distanceInterval of 50 meters... are you moving enough for it to notify you?
  •  Tags:  
  • Related