Search code examples
androidreactjsreact-nativegeolocationandroid-location

React Native Geolocation await function not working


I am trying to get geolocation from the react-native package "@react-native-community/geolocation". on button click I want to get latitude and longitude, for that, I am creating a separate function called getUserCurrentLocation() but I want to make this function as async-await type.

const getUserCurrentLocation = () async => {
   await Geolocation.getCurrentPosition(
      info => {
        setGeo({
          lat: info.coords.latitude,
          long: info.coords.longitude,
        });
        console.log(info.coords.latitude + '#' + info.coords.longitude);  
      },
      error => console.log(error),
      {
        enableHighAccuracy: false,
        timeout: 20000,
        maximumAge: 10,
        distanceFilter: 0,
      },
    );
  };

Solution

  • You need to move async behind the parentheses. that's how to use async and await with try and catch block

    const getUserCurrentLocation = async () => {
     try {
      const info = await Geolocation.getCurrentPosition();
      setGeo({
       lat: info.coords.latitude,
       long: info.coords.longitude,
      });
      console.log(info.coords.latitude + '#' + info.coords.longitude); 
     } catch(error) {
      console.log(error);
     }
    };
    

    but I saw on Documents you don't need to use a promise the is an example and it should work normally: Visit https://github.com/react-native-geolocation/react-native-geolocation/blob/master/example/GeolocationExample.js#:~:text=componentDidMount()%20%7B-,Geolocation.getCurrentPosition(,)%3B,-this.watchID%20%3D%20Geolocation

     Geolocation.getCurrentPosition(
       position => {
        const initialPosition = JSON.stringify(position);
        this.setState({initialPosition});
       },
       error => Alert.alert('Error', JSON.stringify(error)),
       {enableHighAccuracy: true, timeout: 20000, maximumAge: 1000},
        );