Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-native Geolocation. Wait for user's response to request

Tags:

react-native

iOS issue only:

I am using the following code to get the users location.

navigator.geolocation.getCurrentPosition(
(position) => {
  console.log("Native GEO GOOD", position);
  return resolve(position)
},
(err) => {
  console.log("Native GEO BADD", err);
  return reject(err)
},
{ enableHighAccuracy: false, timeout: 5000, maximumAge: 0 },

)

The above code opens a dialog box, from which the user can allow my app to geolocate.

The problem is I want to wait until the user actually responds using the dialog box before calling the error or success callback.

I tried to use: requestAuthorization(). But that just opens the dialog box and I have no way to telling when the user has accepted the request to geolocate.

What I would like to do is ask the users permission to geolocate, then after the user accepts, try to geolocate the user.

But I don't see how to do that using react-native geolocation.

If requestAuthorization() took a callback option for when the user responds to the dialog box, that would solve my issue.

like image 503
Daver Muzaffar Avatar asked Feb 17 '18 02:02

Daver Muzaffar


1 Answers

In React-Native using Expo (https://expo.io) you ask for permissions using a Promise and then act on the promise (hopefully when permission is given).

Permissions.askAsync((Permissions.LOCATION)
  .then(({status}) => {
  //your code here after permission is granted
   });
 );

If you aren't using expo, there is a Component call react-native-permissions (https://github.com/yonahforst/react-native-permissions.git) that allows you to request permissions using a promise like my example but without expo. Their example shows the request setting state to let you know the permissions status which you can act on.

Permissions.request('location', { type: 'always' }).then(response => {
    this.setState({ locationPermission: response })
    })
like image 147
SteveB Avatar answered Nov 15 '22 05:11

SteveB