React Native Expo-Location returns Location service unavailable during initial useEffect
Asked Answered
E

1

2

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.

Evenfall answered 27/8, 2021 at 14:28 Comment(1)
I have a same problem , I think is a problem with permissions for Android 11+; Test this: let BackgroundPermissions = await Location.requestBackgroundPermissionsAsync(); console.log({BackgroundPermissions: BackgroundPermissions});Shannanshannen
A
0

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;
}
Appall answered 27/8, 2021 at 14:55 Comment(2)
I tried implementing this with requestForegroundPermissionsAsync() instead. It works when I try it with an emulator, but it doesn't work with my Realme G90T, and Mi 10. On my phone, it still returns the same error: Location provider is unavailable. Make sure that location services are enabled.Evenfall
that mean the issue is in your location service on your devices. u can check it in device's settingAppall

© 2022 - 2024 — McMap. All rights reserved.