How to track user location in background
Published: 2023-02-18 03:51:12



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/idexowthye4it78i0n72.jpg)

In many mobile apps, it's important to track the user's location to provide location-based services or gather data for analytics purposes. However, tracking the location in the background and sending it to the server can be challenging, especially when the screen is locked or the app is in the background. In this tutorial, we'll learn how to update the user's location in every 15 minutes and send it to the server even when the screen is locked in a React Native app.


## Prerequisites

Before we get started, make sure you have the following installed on your development machine:

Node.js (v10 or later)
React Native CLI
Android Studio (for Android development)
Xcode (for iOS development)

## Step 1: Install necessary packages

First, let's install the necessary packages to track the user's location in the background and schedule a background task. Run the following commands in your terminal:

```
npm install @react-native-community/geolocation
npm install react-native-background-task
```

## Step 2: Grant permissions

Next, we need to grant the necessary permissions to access the device's location. Depending on your target platform, you need to add the following lines to your AndroidManifest.xml and Info.plist files:

AndroidManifest.xml:

```
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
```
Info.plist:

```
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>Location is used to track your movements.</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>Location is used to track your movements.</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>Location is used to track your movements.</string>
<key>UIBackgroundModes</key>
<array>
  <string>fetch</string>
  <string>remote-notification</string>
  <string>location</string>
</array>
```

These permissions allow the app to access the device's location even when the app is in the background or the screen is locked.

## Step 3: Set up background location tracking
Now, let's set up the background location tracking using the Geolocation module from @react-native-community/geolocation. This module provides a way to watch the device's position in the background and receive updates at a given interval.

Here's an example of how you can set up the background location tracking:

```
import Geolocation from '@react-native-community/geolocation';

// Configure Geolocation
Geolocation.setRNConfiguration({
  authorizationLevel: 'always', // Request "always" location permission
  skipPermissionRequests: false, // Prompt for permission if not granted
});

// Watch for position updates
const watchId = Geolocation.watchPosition(
  position => {
    console.log(position);
    // Send the position data to the server
  },
  error => {
    console.log(error);
  },
  {
    distanceFilter: 10, // Minimum distance (in meters) to update the location
    interval: 900000, // Update interval (in milliseconds), which is 15 minutes
    fastestInterval: 300000, // Fastest update interval (in milliseconds)
    accuracy: {
      android: 'highAccuracy',
      ios: 'best',
    },
    showsBackgroundLocationIndicator: true,
    pausesLocationUpdatesAutomatically: false,
    activityType: 'fitness', // Specify the activity type (e.g., 'fitness' or 'other')
    useSignificantChanges: false,
    deferredUpdatesInterval: 0,
    deferredUpdatesDistance: 0,
    foregroundService: {
      notificationTitle: 'Tracking your location',
      notificationBody: 'Enable location tracking to continue', // Add a notification body
    },
  }
);

// To stop tracking (for example, when the component unmounts):
// Geolocation.clearWatch(watchId);

```
By following the steps outlined in this tutorial, you can ensure that your app continues to track the user's location and provide relevant services even when the app is in the background or the screen is locked.