navigator.geolocation:: Location request timed out issue React Native
Asked Answered
G

5

11

I am building a React Native app and trying to get my current geocodes using navigator.geolocation It shows me an error of Location request Time out. Basically I am building a tracking app and I need to configure the exact location latitude longitude. To start tracking there is one button and click of this tracking would be start and it should be the initial point for tracking. I am using default react native geolocation API, Link https://facebook.github.io/react-native/docs/geolocation Function to get my current location::

getLocation() {
    navigator.geolocation.getCurrentPosition(response => {
        console.log(response);
        if (response && response.coords) {
            this.saveLogs(response.coords);
        }
    },
        (error) => {
            this.onGeolocationErrorOccurCallback(error);
        },
        GeolocationOptions
    )
}

It shows me an Error::

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

I have added permission for Android device, and also checking by set enableHighAccuracy value to false. But it's not working for me. And I need to set enableHighAccuracy to true because I want exact geocodes to track someone. Please suggest why Location request timed out is occurring here??

Ganges answered 24/1, 2019 at 9:1 Comment(0)
S
5

UPDATE: 2021 June 12,

This approach works for me in Android Emulator. "react-native": "0.64.1" and Android API 30

import Geolocation from "@react-native-community/geolocation";

const getGeoLocaation = () => {
  const config = {
    enableHighAccuracy: true,
    timeout: 2000,
    maximumAge: 3600000,
  };

  Geolocation.getCurrentPosition(
    info => console.log("INFO", info),
    error => console.log("ERROR", error),
    config,
  );
};
Scalawag answered 11/6, 2021 at 19:8 Comment(1)
You have fixed my problem, thanks!Screed
L
4

The code below worked for me:

componentDidMount(){
   if(Platform.OS === 'android'){
      this.requestLocationPermission()
   }else{
      this._getCurrentLocation()
   }
}

async requestLocationPermission() {
    try {
        const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
        {
          'title': 'Location Permission',
          'message': 'MyMapApp needs access to your location'
        }
        )

       if (granted === PermissionsAndroid.RESULTS.GRANTED) {
           this._getCurrentLocation()
           console.log("Location permission granted")
       } else {
           console.log("Location permission denied")
       }
    } catch (err) {
       console.warn(err)
    }
}

_getCurrentLocation = () =>{
    navigator.geolocation.getCurrentPosition(
       (position) => {
       this.setState({
          latitude: position.coords.latitude,
          longitude: position.coords.longitude, 
       })
    },
    (error) => {
        this.setState({ error: error.message })},
        { enableHighAccuracy: true, timeout: 200000, maximumAge: 1000 },
    );
}

Permission in Manifest file:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Just make sure your location is enabled.

Lustring answered 24/1, 2019 at 9:32 Comment(9)
I have already tried this but its not working on Redmi note 4 | Android 7, MIUI 9 |Bakke
Is it working on any other device? @HarleenKaurAroraLustring
Only moto E-4 plus but I need a working on all devices.Bakke
It's working on ios devices, but there is an issue with the most of Android devices. And I have already set permission and called above function when permission are grantedGanges
Can you tell me how can I resolve this for Android devicesGanges
And I am using default react native geolocation API , If there is any other best API to get exact geocodes? If any please suggest me.Ganges
Sorry, I don't know why it is not working in your case. I tested this on Samsung S4 and Nexus 6P, and it worked for me.Lustring
I have tested on Redmi Note 4, Oppo F1 and Redmi 3S but it's not working.Ganges
This is worked for me .ThanksTelesthesia
R
2

Try to use:

enableHighAccuracy: false

Worked for me!

    const getUserCurrentLocation = () => {
    let latitude, longitude

    Geolocation.getCurrentPosition(
        info => {
            const { coords } = info

            latitude = coords.latitude
            longitude = coords.longitude

            setLat(latitude)
            setLng(longitude)

            getUserCurrentAddress(latitude, longitude)
        },
        error => console.log(error),
        {
            enableHighAccuracy: false,
            timeout: 2000,
            maximumAge: 3600000
        }
    )
}
Restriction answered 4/6, 2021 at 4:39 Comment(0)
O
2

I add the same issue ({"TIMEOUT":3,"POSITION_UNAVAILABLE":2,"PERMISSION_DENIED":1,"message":"Location request timed out", "code":3}) After reading the following documents, https://developer.android.com/training/location/permissions#java https://github.com/react-native-geolocation/react-native-geolocation/blob/master/example/GeolocationExample.js'

I understood that, I need to add:

  • in the manifest AndroidManifest.xml

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 
    

And increment the timeout as follow

    {
        enableHighAccuracy: false,
        timeout: 2000,
        maximumAge: 3600000
    }

   -- code snipet
   Geolocation.getCurrentPosition(
        position => {
          const initialPosition = JSON.stringify(position);
         console.log(initialPosition)
         // this.setState({initialPosition});
        },
      error => console.log('Error', JSON.stringify(error)),
      {enableHighAccuracy: true, timeout: 20000, maximumAge: 1000},
    );
Oleg answered 9/1, 2022 at 18:3 Comment(0)
V
0

In my case i update enableHighAccuracy: true to enableHighAccuracy: false and it worked.

Geolocation.getCurrentPosition(
      (position: any) => {
        const {latitude, longitude} = position.coords;
        setLocation({latitude, longitude});
        mapRef.current?.animateToRegion(
          {
            latitude,
            longitude,
            latitudeDelta: 0.1,
            longitudeDelta: 0.1 * (width / height),
          },
          0,
        );
      },
      (error: any) => {
        Alert.alert(
          'Error',
          'Failed to get current location. Please make sure location services are enabled.',
        );
        console.log('error in current location:', error);
      },
      {enableHighAccuracy: false, timeout: 20000, maximumAge: 3600000},
    );
Vogue answered 8/3 at 12:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.