Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

getCurrentPosition doesn't work on Android. #272

Open
lazyflog opened this issue Sep 5, 2023 · 25 comments
Open

getCurrentPosition doesn't work on Android. #272

lazyflog opened this issue Sep 5, 2023 · 25 comments
Labels
bug Something isn't working

Comments

@lazyflog
Copy link

lazyflog commented Sep 5, 2023

Environment

System:
OS: macOS 13.5.1
CPU: (10) arm64 Apple M1 Max
Memory: 81.98 MB / 32.00 GB
Shell: 5.9 - /bin/zsh
Binaries:
Node: 18.15.0 - ~/.nvm/versions/node/v18.15.0/bin/node
Yarn: 1.22.19 - /opt/homebrew/bin/yarn
npm: 9.5.0 - ~/.nvm/versions/node/v18.15.0/bin/npm
Watchman: 2023.07.24.00 - /opt/homebrew/bin/watchman
Managers:
CocoaPods: 1.12.1 - /Users/yangjongseon/.rbenv/shims/pod
SDKs:
iOS SDK:
Platforms: DriverKit 22.4, iOS 16.4, macOS 13.3, tvOS 16.4, watchOS 9.4
Android SDK: Not Found
IDEs:
Android Studio: Giraffe 2022.3.1 Giraffe 2022.3.1
Xcode: 14.3.1/14E300c - /usr/bin/xcodebuild
Languages:
Java: 11.0.17 - /usr/bin/javac
npmPackages:
@react-native-community/cli: Not Found
react: 18.2.0 => 18.2.0
react-native: 0.71.8 => 0.71.8
react-native-macos: Not Found
npmGlobalPackages:
react-native: Not Found

Platforms

Android

Versions

  • Android: *
  • iOS: *
  • react-native-geolocation: *
  • react-native: *
  • react: *

Description

When I try to get the position by simply using getCurrentPosition, I get the error below on Android only.
enableHighAccuracy: false This works fine, but I want to get the location via GPS.

Reproducible Demo

error {"ACTIVITY_NULL": 4, "PERMISSION_DENIED": 1, "POSITION_UNAVAILABLE": 2, "TIMEOUT": 3, "code": 3, "message": "Location request timed out"}
  const getCurrentLocation = useCallback(
    (timeout = 3000, ignoreError = false) => {
      if (locationPermissionStatus !== LocationPermissionStatus.GRANTED) {
        return;
      }

      Geolocation.getCurrentPosition(
        (position) => {
          console.log('position', position);
          setCurrentLocation(position);
        },
        (error) => {
          console.log('error', error);
          if (ignoreError) {
            return;
          }
          setLocationPermissionStatus(LocationPermissionStatus.SERVICE_DENIED);
        },
        {
          enableHighAccuracy: true,
          timeout,
          maximumAge: 10000,
        },
      );
    },
    [locationPermissionStatus],
  );
@lazyflog lazyflog added the bug Something isn't working label Sep 5, 2023
@darkosimic025
Copy link

Same here!

@nafeelcassim
Copy link

I have this same issue, but when u set enableHighAccuracy: false, it will work or else try removing the maximumAge parameter. But when maximumAge parameter was removed my accuracy of location was very bad comparing to when enableHighAccuracy was set to false.

@dgreasi
Copy link

dgreasi commented Sep 19, 2023

Having the same issue in version v2.1.0 on Android only ("react-native": "0.68.2")

The error seems similar:

{
  TIMEOUT: 3,
  POSITION_UNAVAILABLE: 2,
  PERMISSION_DENIED: 1,
  message: 'Location permission was not granted.',
  code: 1
}

I am guessing for my case the library is not detecting that I have allowed the location permission. I tried in different ways but it's always the same.

After upgrading to the latest version v3.1.0, I am getting wait time about 3-4 seconds for the getCurrentPosition() to resolve and it is throwing the following error (which seems almost the same):

{ 
  TIMEOUT: 3,
  POSITION_UNAVAILABLE: 2,
  PERMISSION_DENIED: 1,
  message: 'Location request timed out',
  ACTIVITY_NULL: 4,
  code: 3
}

In my code I have tried all the possible scenarios.

  • For the permissions part in AndroidManifest
    • Use only ACCESS_COARSE_LOCATION
    • Use only ACCESS_FINE_LOCATION
    • Use both
    • Use none
  • For requesting the above permissions each time I am using the following, again in all possible combinations with the previous part:
PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION);
# OR
PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION);

Always after accepting the permission request on the OS dialogs, I get the correct response from the PermissionsAndroid.request(), which is the following:

PermissionsAndroid.RESULTS.GRANTED

Nevertheless, the geolocation library seems to have a different opinion on that matter. Also, I checked the settings of the app and the location permissions are granted, which means that the PermissionsAndroid.request() is working correctly.

Also if you try using Geolocation.requestAuthorization(), before or after requesting permissions with the previous way, the following error is thrown:

TypeError: _$$_REQUIRE(_dependencyMap[3], "./nativeInterface").RNCGeolocation.requestAuthorization is not a function. (In '_$$_REQUIRE(_dependencyMap[3], "./nativeInterface").RNCGeolocation.requestAuthorization()', '_$$_REQUIRE(_dependencyMap[3], "./nativeInterface").RNCGeolocation.requestAuthorization' is undefined)

Tested on Pixel 6a, Pixel 4a both with Android 13.

For iOS everything works as expected.

@skizzo
Copy link

skizzo commented Sep 26, 2023

Any way to make this library actually work on Android?

@glanceon
Copy link

from google search = "ACCESS_FINE_LOCATION includes GPS data in reporting user location while ACCESS_COARSE_LOCATION includes data from the most battery-efficient non-GPS provider available (e.g., the network)."

I left only ACCESS_FINE_LOCATION permission in AndroidMainfest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

I have removed maximumAge and set enableHighAccuracy to false

useEffect(() => {
    Geolocation.getCurrentPosition(
      (position) => {
        console.log(position.coords)
      },
      (error) => {
        console.error(error);
      },
      {
        enableHighAccuracy: false,
        timeout: 10000,
      }
    );
  }, []);

Tested on 2 android 11 devices, both were accurate

@singhagam1
Copy link

Same issue on

"react-native": "0.71.12",
"@react-native-community/geolocation": "3.1.0",

Works pretty well on iOS.

Anyone with a workaround ?

@lazyflog
Copy link
Author

lazyflog commented Oct 13, 2023

from google search = "ACCESS_FINE_LOCATION includes GPS data in reporting user location while ACCESS_COARSE_LOCATION includes data from the most battery-efficient non-GPS provider available (e.g., the network)."

I left only ACCESS_FINE_LOCATION permission in AndroidMainfest.xml <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

I have removed maximumAge and set enableHighAccuracy to false

useEffect(() => {
    Geolocation.getCurrentPosition(
      (position) => {
        console.log(position.coords)
      },
      (error) => {
        console.error(error);
      },
      {
        enableHighAccuracy: false,
        timeout: 10000,
      }
    );
  }, []);

Tested on 2 android 11 devices, both were accurate

I'm mistaken, this doesn't work for me.

I checked in AndroidStudio and found that
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
is required to call <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>.

@lazyflog lazyflog reopened this Oct 13, 2023
@jacquesdev
Copy link

So just to confirm @lazyflog - this seems to be an issue on Android where setting enableHighAccuracy to true will always time out? This is what I'm experiencing from my side.

@michalchudziak - do you have any idea why this could be?

@luchoeli
Copy link

luchoeli commented Nov 6, 2023

disabling hight accuracy worked for me.

@Knorway
Copy link

Knorway commented Nov 7, 2023

set enableHighAccuracy: false works for me on android. wonder it started to happen recently since it is not documented.

@wmonecke
Copy link

Any updates on this?

@veb-ioki
Copy link

Same for us as in the issue description from @lazyflog.
We need enabled enableHighAccuracy: true though.

@KevDanCC
Copy link

KevDanCC commented Jan 20, 2024

In some how, that's be appear if your're working with your device in a inside of building and the GPS signal cannot get. So you have 2 options: Try with enableHighAccuracy: false or, comment the timeout:

  },
            {
                enableHighAccuracy: true, // Optional: Enable high-accuracy mode
                // timeout: 15000,           // Optional: Set a timeout (in milliseconds) for the request
            }
        );

That's gonna to do more time to your device to get the GPS Signal. That work's for me.

@vignesh-sprybe
Copy link

Hey guys. I had the same problem and was wondering what was happening. I see this setting
locationProvider (string, Android-only) - Either "playServices", "android", or "auto". Determines wether to use Google’s Location Services API or Android’s Location API. The "auto" mode defaults to android, and falls back to Android's Location API if play services aren't available.

https://www.npmjs.com/package/@react-native-community/geolocation#setrnconfiguration

After setting this in Geolocation.setRNConfiguration, this problem goes away and its working in all android versions. The problem is that, the emulators in android studio doesn't come with Google play APIs. I think this comes only from API level 33 (Android 13). Older emulators come with just Google APIs. So this setting helps to fall back to android and provide the location information. Please test in your code let me know. Eager to know.

@amjadbouhouch
Copy link

+1

@DimaBarokha
Copy link

Same issue(

@LouisKraemer
Copy link

We have the same issue, I can provide log if needed.
Any update?

@dgreasi
Copy link

dgreasi commented Apr 14, 2024

I didn't find a way to solve it in my case.

I switched to that: react-native-geolocation-service, and it's working as expected for me.

@Anhunghezo
Copy link

I didn't find a way to solve it in my case.

I switched to that: react-native-geolocation-service, and it's working as expected for me.

Did you get same coords for both of this library?

@lazyflog
Copy link
Author

I switched to the react-native-geolocation-service to get the desired behavior, but it seems to have been unmaintained for a while, so it's not a long-term solution.

@ucvdesh
Copy link

ucvdesh commented Jul 25, 2024

I just had this same error, for me it was the maximumAge but I can leave enableHighAccuracy true or false, but is more accurate on false than true (?

@mtebele
Copy link

mtebele commented Sep 4, 2024

Same here! Any solution?

@israr002
Copy link

The issue is not resolved yet even in the latest version

@namhac-pionero
Copy link

namhac-pionero commented Oct 28, 2024

image maybe you need to request for background permission

 const requestLocationPermissions = async () => {
    try {
      const granted = await requestMultiple([
        PERMISSIONS.ANDROID.ACCESS_COARSE_LOCATION,
        PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION,
      ]);
      if (
        granted[PERMISSIONS.ANDROID.ACCESS_COARSE_LOCATION] === 'granted' &&
        granted[PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION] === 'granted'
      ) {
        await request(PERMISSIONS.ANDROID.ACCESS_BACKGROUND_LOCATION).then(
          permission => {
            if (permission === 'granted') {
              setGrantedPermission(true);
            }
          },
        );
        return;
      }
    } catch {
      setGrantedPermission(false);
    }

@AkilUnik
Copy link

`const requestLocationPermission = async () => {
if (Platform.OS === 'android' && Platform.Version >= 23) {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
title: 'Location Permission',
message: 'App needs access to your location',
buttonNeutral: 'Ask Me Later',
buttonNegative: 'Cancel',
buttonPositive: 'OK',
},
);
return granted === PermissionsAndroid.RESULTS.GRANTED;
} catch (err) {
console.warn(err);
return false;
}
}
return true;
};

export const getLocation = async () => {
// First, check and request permissions
const hasLocationPermission = await requestLocationPermission();

if (!hasLocationPermission) {
console.log('Location permission denied');
return;
}

// Configure geolocation
Geolocation.setRNConfiguration({
skipPermissionRequests: false,
authorizationLevel: 'whenInUse', // or 'always'
});

// Get current position
Geolocation.getCurrentPosition(
position => {
console.log('Position:', position);
const {latitude, longitude} = position.coords;
console.log(Latitude: ${latitude}, Longitude: ${longitude});
},
error => {
console.log('GetCurrentPosition Error:', error);
// Comprehensive error handling
switch (error.code) {
case 1:
console.log('Permission denied');
break;
case 2:
console.log('Position unavailable');
break;
case 3:
console.log('Timeout');
break;
default:
console.log('Unknown error');
}
},
{
enableHighAccuracy: false,
timeout: 10000, // 30 seconds
},
);
};`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests