Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you track background geolocation with React Native?

Problem

I'd like to be able to track a users location even when the app is no longer in the foreground (e.g. The user has switch to another app or switched to the home screen and locked their phone).

The use case would be a user tracking a run. They could open the app and press 'start' at the beginning of their run, then switch or minimise the app (press the home button) and lock the screen. At the end of the run they could bring the app into the foreground and press 'stop' and the app would tell them distance travelled on the run.

Question

Is tracking background geolocation possible on both iOS and Android using pure react native?

The react native docs on geolocation (https://facebook.github.io/react-native/docs/geolocation) are not very clear or detailed. The documented linked above eludes to background geolocation on iOS (without being fully clear) but does not mention Android.

Would it be best that I use Expo?

like image 806
Grant Avatar asked Feb 21 '19 16:02

Grant


People also ask

Does React Native support geolocation?

Geolocation is enabled by default when you create a project with react-native init . In order to enable geolocation in the background, you need to include the 'NSLocationAlwaysUsageDescription' key in Info. plist and add location as a background mode in the 'Capabilities' tab in Xcode.

How does app detect background in React Native?

This is an example to Get Application State using AppState in React Native. React Native AppState helps you to know the currents state of the application. It will give you the information that the application is in the foreground or in the background, and will notify you on the change of state.


1 Answers

The most popular RN geolocation library is https://github.com/react-native-geolocation/react-native-geolocation, and it supports this quite easily. I prefer this library over others because it automatically handles asking for permissions and such, and seems to have the simplest API.

Just do this:

Geolocation.watchPosition((position)=>{
    const {latitude, longitude} = position.coords;
    // Do something.
})

This requires no additional setup other than including the background modes fetch and location, and also the appropriate usage descriptions.

I find this more usable than Expo's API because it doesn't require any weird top level code and also doesn't require me to do anything other than create a watch position handler, which is really nice.

like image 86
ICW Avatar answered Sep 27 '22 18:09

ICW