Home > Mobile >  expo-location (React-Native) : Location.getCurrentPositionAsync() never returns anything
expo-location (React-Native) : Location.getCurrentPositionAsync() never returns anything

Time:11-16

I'm developing a cross platform mobile App.

I'm testing my code on a Android Studio emulator (google pixel 5, api level 30) and i'm using expo version : ~43.0.2 and expo-location version : ~13.0.4

I've already asked for the location permission, and it works. But when I call the following code i log "there" but never "here":

        console.log("there")
        const userLocation = await Location.getCurrentPositionAsync()
        console.log("here")

Indeed, the function Location.getCurrentPositionAsync() seems locked

A similar issue has been know in the past according to these links:

React Native Expo-Location returns Location service unavailable during initial useEffect https://forums.expo.dev/t/getcurrentpositionasync-doesnt-return-any-value-infinity-loading/23643

But it's also the code in the Expo doc :

https://snack.expo.dev/@charliecruzan/expo-map-and-location-example

. Bellow the entire app class :


import { StatusBar } from 'expo-status-bar';
import React from 'react';
import {Text, TextInput, Pressable, View, Alert} from 'react-native';
import * as Location from "expo-location"


export default class App extends React.Component{
    state = {
        errorMessage: "",
        location: {}
    }

    getAddress(){
        return this.state.address
    }

    _getLocation = async ()=>{
        const {status} = await Location.requestForegroundPermissionsAsync();
        if (status !== "granted"){
            console.log("PERMISSION LACK!")
            this.setState({
                errorMessage:"PERMISSION NOT GRANTED"
            });
        }
        console.log("there")
        const userLocation = await Location.getCurrentPositionAsync();
        console.log("here")
        console.log(JSON.stringify(userLocation))
        this.setState({
            location: userLocation
        })
    }

    render(){
        this._getLocation()

        return (
            <View>
                 <Text>Salut</Text>
            </View>
        );
    }
}


What did i missed?

CodePudding user response:

Add accuracy and maximumAge in parameters with Location.Accuracy.Highest and 10000 respectively as shown below:

JavaScript:

const userLocation = await Location.getCurrentPositionAsync({accuracy: Location.Accuracy.Highest, maximumAge: 10000});

The solution came from How to use getCurrentPositionAsync function in expo-location | Tabnine.

  • Related