Search code examples
react-nativegeolocation

get current location in first run


I have an app that uses location services but when I request for current location and after user allowed permission, app could not find location. for user to find it's location must close and re-open the app till find correct position. here's my code :

componentWillMount() {
    this.getCurrentLocation();
}
getCurrentLocation = () => {
    const locationConfig = {
        timeout: 20000,
        maximumAge: 1000,
        enableHighAccuracy: false
    };
    navigator.geolocation.getCurrentPosition(
        this.iGetLocation,
        (error) => {
            console.log(error);
        },
        locationConfig
    );
};

Solution

  • I think the issue is in your position callback: this.iGetPosition. Try to use a callback function, like below. This is working for me(check the getCurrentPosition function):

     componentDidMount() {
            this.requestAccess();
     }
     requestAccess = async () => {
        try {
          const granted = await PermissionsAndroid.request(
            PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
            {
              'title': 'Location permission',
              'message': 'App needs access to your location ' +
                         'so we can show your location.'
            }
          )
          if (granted === PermissionsAndroid.RESULTS.GRANTED) {
            navigator.geolocation.getCurrentPosition(
              (position) => {
                this.setState({
                  latitude: position.coords.latitude,
                  longitude: position.coords.longitude,
                  error: null,
                });
              },
              (error) => this.setState({ error: error.message }),
              { enableHighAccuracy: false, timeout: 20000, maximumAge: 1000 },
            );
    
          } else {
            console.log("Location permission denied")
          }
        } catch (err) {
          console.warn(err)
        }
      }