React Native Expo-Location returns Location service unavailable during initial useEffect

Viewed 1667

Main Problem: I am using expo-location in my Android app in order to find the gps coordinates of the user. I have read and used the sample code provided in the expo documentation. My main problem is that, Location.getCurrentPositionAsync({}) returns Location provider is unavailable. Make sure that location services are enabled. This is my code below:

useEffect(() => {
    (async () => {
      let { status } = await Location.requestForegroundPermissionsAsync();
      if (status !== 'granted') {
        setErrorMsg('Permission to access location was denied');
        return;
      }
      let location = await Location.getCurrentPositionAsync({});
      console.log(location);
    })();
  }, []);

Status returns granted but getCurrentPositionAsync({}) returns an error. I implemented a janky solution by using try-catch blocks and running getCurrentPositionAsync({}) again in the catch block, which seems to work. This is my code below:

useEffect(() => {
    (async () => {
      let { status } = await Location.requestForegroundPermissionsAsync();
      if (status !== 'granted') {
        setErrorMsg('Permission to access location was denied');
        return;
      }
      try {
        var location = await Location.getCurrentPositionAsync({});
      } catch {
        location = await Location.getCurrentPositionAsync({});
      }
      console.log(location);
    })();
  }, []);

Does anyone know why this is happening?

EDIT: I tried to run the sample code posted in the expo-location documentation using their snack example. Same result. Could this be a problem with my phone/area? I've tested it with two phones, and both return the same error.

1 Answers

I think location variable can't log / use directly and this is the way that I retrieve location:

let { status } = await Location.requestPermissionsAsync();
let location = await Location.getCurrentPositionAsync({});

if (status !== 'granted') setErrorMsg('...');

const { coords } = location;

if (coords) {
   const { latitude, longitude } = coords;
}
Related