# react-native-geolocation-pro

Production-grade React Native GPS for **high-performance tracking apps** — background location, native SQLite persistence, motion auto-pause, geofencing, and built-in Live Activities support.

Built as an open-source (MIT) alternative to Transistorsoft `react-native-background-geolocation`, tailored for delivery, logistics, navigation, and high-frequency fitness apps.

```bash
npm install react-native-geolocation-pro
cd ios && pod install
```

## Why this package?

Building a reliable background location tracking library for React Native is incredibly difficult due to aggressive OS-level battery optimizations. This package solves the hardest problems natively:

1. **Native SQLite Persistence**: Both iOS and Android store coordinates natively first, then drain them to the JS thread. No data is lost if the React Native bridge crashes or is paused by the OS.
2. **Battery-Conscious Motion Detection**: Includes native `MotionEngine`s (CoreMotion / Activity Recognition) that automatically suspend the GPS hardware when the device is stationary to save battery, waking it up when movement resumes.
3. **Advanced Integrations**: High-performance distance filtering, intelligent auto-pause, and out-of-the-box support for iOS 16+ Live Activities and Dynamic Island.

It offers two APIs: a standard drop-in replacement for `@react-native-community/geolocation`, and a powerful `BackgroundGeolocation` API for full session orchestration.

## Platform support

| Feature | iOS | Android |
|---------|-----|---------|
| `getCurrentPosition` / `watchPosition` | ✅ | ✅ |
| Background GPS + SQLite queue | ✅ | ✅ |
| Built-in foreground tracking service | — | ✅ |
| Foreground queue replay | ✅ | ✅ |
| Watch restore after app restart | ✅ | ✅ |
| `distanceFilter`, `interval`, `maximumAge` | ✅ | ✅ |
| Motion auto-pause (`MotionEngine`) | ✅ | 🚧 scaffold |
| `CLBackgroundActivitySession` (iOS 17+) | ✅ | — |
| Live Activities (iOS 16+) | ✅ | — |

## Quick start

```javascript
import Geolocation from 'react-native-geolocation-pro';

// One-shot location (map pin, start screen)
Geolocation.getCurrentPosition(
  position => console.log(position.coords),
  error => console.warn(error),
  { enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 },
);

// Continuous tracking in the background
const watchId = Geolocation.watchPosition(
  position => saveRoutePoint(position),
  error => console.warn(error),
  {
    enableHighAccuracy: true,
    distanceFilter: 5,
    interval: 3000,
    fastestInterval: 1000,
    showsBackgroundLocationIndicator: true, // Enables the blue pill on iOS without needing "Always" permission!
  },
);

// Stop
Geolocation.clearWatch(watchId);
```

## Live Activities (iOS)

This package natively integrates with iOS Live Activities to display real-time tracking data on the Lock Screen and Dynamic Island!

For a full guide on generating your Xcode Widget Target and connecting it to this package, please see our dedicated guides:
- [Live Activity Quick Start](./LIVE-ACTIVITY-QUICK-START.md)
- [Live Activity Advanced Guide](./LIVE-ACTIVITY-GUIDE.md)

## Permissions

Use built-in helpers or your own flow:

```javascript
import { PermissionManager } from 'react-native-geolocation-pro';

const result = await PermissionManager.requestPermissions({
  includeMotion: true, // Android ACTIVITY_RECOGNITION
});

if (result.status !== 'ready') {
  await PermissionManager.openSettings();
}
```

## Background tracking

GPS continues in the background. Points collected while JS is suspended are stored in **native SQLite** and replayed when the app returns to foreground — no data loss on lock screen.

```javascript
// Manual sync (usually automatic via AppState)
const count = await Geolocation.syncPendingLocations();
console.log(`Delivered ${count} queued points`);
```

### Production lifecycle API

For complex tracking orchestration, use the native-first lifecycle API. This gives the app a clear state machine: configure, subscribe, start native recording, sync the native SQLite queue, then stop.

```javascript
import { BackgroundGeolocation } from 'react-native-geolocation-pro';

const sub = BackgroundGeolocation.onLocation(
  async location => {
    await saveCoordinateToDatabase(location);
  },
  error => console.warn(error),
);

await BackgroundGeolocation.ready({
  authorizationLevel: 'whenInUse',
  enableHighAccuracy: true,
  desiredAccuracy: 10,
  distanceFilter: 0,
  locationUpdateInterval: 1000,
  fastestLocationUpdateInterval: 1000,
  trackingMode: 'navigation', // or 'fitness', 'balanced'
  pausesLocationUpdatesAutomatically: false,
  showsBackgroundLocationIndicator: true,
  notificationTitle: 'Live Tracking Active',
  notificationText: 'Recording your route in the background',
});

await BackgroundGeolocation.start();

// End tracking
await BackgroundGeolocation.sync();
await BackgroundGeolocation.stop();
sub.remove();
```

**Required setup:** See [docs/SETUP.md](./docs/SETUP.md) for Info.plist and AndroidManifest snippets.

Verify your app:

```bash
npx react-native-geolocation-pro verify-setup
```

## Migration from @react-native-community/geolocation

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

Same API: `getCurrentPosition`, `watchPosition`, `clearWatch`, `requestAuthorization`, `setRNConfiguration`.

See [docs/MIGRATION.md](./docs/MIGRATION.md) for options matrix and edge cases.

## API reference

### Geolocation (default export)

| Method | Description |
|--------|-------------|
| `getCurrentPosition(success, error?, options?)` | Single fix with `timeout`, `maximumAge` |
| `watchPosition(success, error?, options?)` → `number` | Continuous updates |
| `clearWatch(id)` | Stop one watch |
| `stopObserving()` | Force stop all watches & Live Activities |
| `requestAuthorization(level?)` | `'whenInUse'` \| `'always'` |
| `getAuthorizationStatus()` | `{ status, always }` |
| `setRNConfiguration(config)` | Global config |
| `syncPendingLocations()` | Drain SQLite queue to callbacks |
| `getQueueSize()` | Pending point count |
| `addAuthorizationListener(cb)` | Permission change events |

### Options (`GeolocationOptions`)

| Option | Default | Notes |
|--------|---------|-------|
| `timeout` | 15000 | ms, emits error code `3` |
| `maximumAge` | 0 | Accept cached fix if younger (ms) |
| `enableHighAccuracy` | true | |
| `showsBackgroundLocationIndicator`| false | Set to `true` to show iOS Blue pill without 'Always' permissions |
| `distanceFilter` | 5 | meters |
| `interval` | 3000 | Android update interval (ms); iOS is distance/accuracy driven |
| `fastestInterval` | 1000 | Android min interval (ms) |
| `trackingMode` | — | `fitness` \| `navigation` \| `balanced` \| `low_power` |
| `enableMotion` | false | Opt-in motion engine with watch |

## Docs

| Doc | Description |
|-----|-------------|
| [docs/SETUP.md](./docs/SETUP.md) | Platform permissions |
| [docs/MIGRATION.md](./docs/MIGRATION.md) | From community geolocation |
| [LIVE-ACTIVITY-QUICK-START.md](./LIVE-ACTIVITY-QUICK-START.md) | Live Activities |

## Requirements

- React Native ≥ 0.73
- iOS 13+ (iOS 16+ for Live Activities)
- Android API 24+
- Bare workflow or Expo dev client (native module)

MIT · [Arslan Khan](https://github.com/Arslankhan9000)
