Unexpected coordinates returned from Location.watchPositionAsync

Please provide the following:

  1. SDK Version: 37.0.3
  2. Platforms(Android/iOS/web/all): iOS

So I am currently trying to set up a distance tracker that will start tracking a user’s distance on a button click. In other words, the app should only start tracking distance AFTER this button has been clicked.

After debugging I have found that the first two coordinates are the original location when the user OPENED the app, not when I click Start. I have debugged and tested via iOS simulator.

I’ve tried to minimize the code to only the parts pertaining to the problem, and made comments at the buggy parts below. A full working example can be found at this Snack: watchPositionASync Problem - Snack

// excluded imports 
const LATITUDE = 37.7749;
const LONGITUDE = -122.4194;
const LATITUDE_DELTA = 0.00922;
const LONGITUDE_DELTA = 0.00421;

// keeps track of return object of watchPositionAsync
let location = null;

// keeps track of number of coordinates tracked
// important because right now there is a bug where the original location is being added
let count = 0;

export default function App() {
  const [region, setRegion] = useState({
    latitude: LATITUDE,
    longitude: LONGITUDE,
    latitudeDelta: LATITUDE_DELTA,
    longitudeDelta: LONGITUDE_DELTA,
  });
  // state keeping track of whether we have clicked start or not
  const [before, setBefore] = useState(true);
  const [errorMsg, setErrorMsg] = useState(null);
  const [routeCoordinates, setRouteCoordinates] = useState([]);

  const getLocationAsync = async () => {
    const { status } = await Permissions.askAsync(Permissions.LOCATION);
    if (status === "granted") {
      location = await Location.watchPositionAsync(
        {
          accuracy: Location.Accuracy.High,
          distanceInterval: 30,
        },
        (newLocation) => {
          let coords = newLocation.coords;
          const newRegion = {
            latitude: coords.latitude,
            longitude: coords.longitude,
            latitudeDelta: LATITUDE_DELTA,
            longitudeDelta: LONGITUDE_DELTA,
          };
          setRegion(() => newRegion);
          let newLoc = {
            latitude: coords.latitude,
            longitude: coords.longitude,
          };

          // keeps track of the number of coordinates
          // BUG: After debugging, I have found that right now, the first and second coordinates within the variable routeCoordinates are always the original location when the user opens the app. I'd like this list to only be updated AFTER the user clicks start.
          // workaround is just to ignore the first and second coordinates right now
          // commented out for reference, you can uncomment to test what is expected behavior
          // if (count !== 0 && count !== 1) {
          //   setRouteCoordinates((oldCoordinates) => [
          //     ...oldCoordinates,
          //     newLoc,
          //   ]);
          // }
          // count++;
          // ideally just this line would work instead of the lines above
          setRouteCoordinates((oldCoordinates) => [...oldCoordinates, newLoc]);
        },
        (error) => console.log(error)
      );
    } else {
      setErrorMsg("Location services needed");
    }
  };

  // starts tracking async locations whenever before state is changed in onPress
  useEffect(() => {
    if (before === false) {
      getLocationAsync();
    }
  }, [before]);


  return errorMsg ? (
    <Text>{errorMsg}</Text>
  ) : (
    <View style={styles.container}>
      {before ? null : (
        <MapView style={styles.map} region={region}>
          <Polyline coordinates={routeCoordinates}></Polyline>
        </MapView>
      )}
      <View style={styles.buttonContainer}>
        {before ? (
          <Button
            title="Start"
            onPress={() => {
              setBefore(false);
            }}
          ></Button>
        ) : (
          <Button
            title="Stop"
          ></Button>
        )}
      </View>
    </View>
  );
}

If anyone has any insights as to why this is happening I would greatly appreciate it!

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.