Production-ready React Native SDK for enterprise-grade background location tracking. Built with offline-first architecture, journey tracking, geofencing, and intelligent battery optimization. Perfect for fleet management, employee tracking, delivery apps, and field service applications.
- Platform Support
- Features
- Quick Start
- Installation
- Platform Setup
- Basic Usage
- Configuration
- Documentation
- Requirements
- Use Cases
- Battery Optimization
- Backend Integration
- Troubleshooting
- Contributing
- License
- Support
| Platform | Status | Version | NPM Tag |
|---|---|---|---|
| π€ Android | β Fully Supported | 1.0.0+ | @latest |
| π iOS | β Fully Supported | 1.0.0+ | @latest |
npm install nawcrest-react-native-location-sdkBoth Android and iOS are fully supported as of v1.0.0. See Platform Setup for the per-platform configuration steps.
- π Background Location Tracking - Continuous, reliable tracking across all app states (foreground, background, terminated, screen locked)
- πΊοΈ High-Accuracy Positioning - Leverages Google Play Services Fused Location Provider for optimal accuracy
- π± Foreground Service - Persistent notification ensures tracking reliability on Android
- π Auto-Restart - Automatically resumes tracking after device reboot
- βΈοΈ Pause & Resume - Temporarily suspend tracking without losing state
- π Encrypted Local Storage - SQLCipher database with AES-256 encryption
- π¦ Offline Queue - Automatic queuing when network unavailable
- π Smart Sync - Background synchronization with exponential backoff retry
- πͺ Resilient - Never lose location data, even with poor connectivity
- ποΈ Database Management - Automatic cleanup and size management
- π Complete Analytics - Distance, duration, average speed, max speed
- π£οΈ Path Recording - Full coordinate path with polyline encoding
- β―οΈ Pause & Resume - Pause journeys without losing data
- π·οΈ Custom Metadata - Attach custom data (order IDs, driver info, etc.)
- π Historical Queries - Filter and retrieve past journeys
- β Circular Geofences - Define zones with center point and radius
- π· Polygon Geofences - Create complex shapes with multiple coordinates
- πͺ Entry & Exit Detection - Real-time events when entering/exiting zones
- β±οΈ Dwell Time Support - Detect when user stays in zone for specified duration
- π Unlimited Geofences - No limit on number of monitored zones
- π·οΈ Custom Metadata - Attach business logic to each geofence
- ποΈ Three Battery Modes - Low, Balanced, High (5-30% battery/24hrs)
- πΆ Activity Recognition - Detects walking, running, driving, cycling, still
- π Smart Throttling - Reduces GPS polling when user is stationary
- β‘ Dynamic Adjustment - Automatically optimizes based on device motion
- π Battery Event Monitoring - Alerts when battery is low
- π Auto-Sync with Retry - Periodic background sync with WorkManager
- π€ Batch Uploads - Efficient batch processing reduces network overhead
- π Exponential Backoff - Smart retry logic for failed uploads
- π Certificate Pinning - Enhanced security with SSL pinning support
- π Token Authentication - JWT, Bearer token, and custom header support
- π² Push-Triggered Location - Fetch location on-demand via FCM push notification
- π¨ Remote Location Requests - Backend can request current location anytime
- π Instant Delivery - Sub-second response time for urgent requests
- π End-to-End Encryption - AES-256 encrypted database
- π Certificate Pinning - Prevent man-in-the-middle attacks
- π Secure Credential Storage - API keys and tokens stored securely
- π‘οΈ Mock Location Detection - Detect and flag fake GPS data
- β Data Validation - Server-side validation prevents bad data
- β‘ TurboModules - Built on React Native's new architecture for maximum performance
- π₯ Hermes Engine - Optimized for Hermes JavaScript engine
- π± Native Performance - Direct native bridge with minimal overhead
- π Synchronous APIs - Fast, synchronous method calls where appropriate
- π TypeScript First - Full TypeScript definitions and type safety
- π Comprehensive Docs - Complete API reference and guides
- π§ͺ Battle-Tested - Production-ready, used in real enterprise apps
- π Debug Tools - Built-in logging and debugging utilities
- π Rich Examples - Real-world code examples for every feature
Get up and running in less than 5 minutes:
# Using npm
npm install nawcrest-react-native-location-sdk
# Using yarn
yarn add nawcrest-react-native-location-sdkimport { PermissionsAndroid, Platform } from 'react-native';
async function requestPermissions() {
if (Platform.OS === 'android') {
await PermissionsAndroid.requestMultiple([
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION,
PermissionsAndroid.PERMISSIONS.ACCESS_BACKGROUND_LOCATION, // Android 10+
]);
}
}import { LocationSDK } from 'nawcrest-react-native-location-sdk';
const sdk = new LocationSDK();
// Initialize
await sdk.initialize({
apiKey: 'your-api-key',
uploadEndpoint: 'https://api.yourcompany.com/locations',
trackingInterval: 10000, // 10 seconds
distanceFilter: 20, // 20 meters
accuracy: 'high',
enableBackgroundTracking: true,
});
// Start tracking
await sdk.start();
// Listen for location updates
sdk.addEventListener('location', (location) => {
console.log('New location:', location.latitude, location.longitude);
});That's it! Your app is now tracking location in the background. See Full Documentation for advanced features.
npm install nawcrest-react-native-location-sdkyarn add nawcrest-react-native-location-sdk- Package Name:
nawcrest-react-native-location-sdk - Current Version: 1.0.0
- NPM Tag:
@latest(Android + iOS) - License: MIT
Complete Android setup requires 3 steps: dependencies, permissions, and configuration. Full setup guide: docs/SETUP_GUIDE.md
1. Add Dependencies (android/app/build.gradle):
dependencies {
implementation "com.google.android.gms:play-services-location:21.1.0"
implementation "net.zetetic:android-database-sqlcipher:4.5.4"
implementation "androidx.work:work-runtime-ktx:2.9.0"
}2. Add Permissions (android/app/src/main/AndroidManifest.xml):
<manifest>
<!-- Location -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<!-- Foreground Service -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_LOCATION" />
<!-- Background -->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<!-- Network -->
<uses-permission android:name="android.permission.INTERNET" />
</manifest>3. Request Runtime Permissions:
See Quick Start section above.
π Complete Setup Instructions: docs/SETUP_GUIDE.md
iOS support coming in v2.0.0. Setup instructions will be provided with iOS release.
import { LocationSDK } from 'nawcrest-react-native-location-sdk';
import type { Location } from 'nawcrest-react-native-location-sdk';
const sdk = new LocationSDK();
// Initialize SDK
await sdk.initialize({
apiKey: 'your-api-key',
uploadEndpoint: 'https://api.yourcompany.com/locations',
employeeId: 'user-123',
trackingInterval: 10000, // 10 seconds
distanceFilter: 20, // 20 meters
accuracy: 'high',
enableBackgroundTracking: true,
enableOfflineSync: true,
batteryMode: 'balanced',
});
// Start tracking
await sdk.start();
// Listen for location updates
sdk.addEventListener('location', (location: Location) => {
console.log('New location:', location.latitude, location.longitude);
});
// Stop tracking
await sdk.stop();// Start a delivery journey
const journeyId = await sdk.startJourney({
purpose: 'delivery',
orderId: '12345',
driverId: 'DRIVER-001',
});
console.log('Journey started:', journeyId);
// ... driving ...
// Stop journey and get analytics
const journey = await sdk.stopJourney(journeyId);
console.log('Distance:', journey.distance, 'meters');
console.log('Duration:', journey.duration / 60000, 'minutes');
console.log('Average speed:', journey.averageSpeed * 3.6, 'km/h');// Create a circular geofence
const geofenceId = await sdk.addGeofence({
type: 'circle',
center: { latitude: 37.7749, longitude: -122.4194 },
radius: 100, // 100 meters
dwellTime: 60000, // 1 minute
metadata: { name: 'Office', location: 'HQ' },
});
// Listen for geofence events
sdk.addEventListener('geofenceEnter', (event) => {
console.log('Entered geofence:', event.geofenceId);
});
sdk.addEventListener('geofenceExit', (event) => {
console.log('Exited geofence:', event.geofenceId);
});π More Examples: docs/USAGE_EXAMPLES.md
The SDK provides comprehensive configuration to customize tracking behavior:
interface SDKConfiguration {
// ========== REQUIRED ==========
apiKey: string; // Your API authentication key
uploadEndpoint: string; // Backend URL for location uploads
// ========== OPTIONAL IDENTITY ==========
employeeId?: string; // User/employee identifier
// ========== TRACKING PARAMETERS ==========
trackingInterval?: number; // Update interval (ms, default: 10000)
distanceFilter?: number; // Min distance change (meters, default: 20)
accuracy?: AccuracyLevel; // 'low'|'medium'|'high'|'best' (default: 'high')
// ========== FEATURE FLAGS ==========
enableBackgroundTracking?: boolean; // Background tracking (default: true)
enableOfflineSync?: boolean; // Offline queue (default: true)
enableJourneyTracking?: boolean; // Journey features (default: false)
enableGeofencing?: boolean; // Geofencing (default: false)
enableActivityRecognition?: boolean; // Activity detection (default: false)
enableRemoteLocationRequest?: boolean; // Push-triggered location (default: false)
enableBatteryOptimization?: boolean; // Battery optimization (default: true)
// ========== SYNC CONFIGURATION ==========
syncInterval?: number; // Auto-sync interval (ms, default: 60000)
retryCount?: number; // Max retry attempts (default: 3)
retryDelay?: number; // Base retry delay (ms, default: 5000)
// ========== AUTHENTICATION ==========
authToken?: string; // JWT or bearer token
// ========== NETWORK ==========
customHeaders?: Record<string, string>; // Custom HTTP headers
requestTimeout?: number; // Request timeout (ms, default: 30000)
enableCertificatePinning?: boolean; // SSL pinning (default: false)
certificateHashes?: string[]; // Certificate SHA-256 hashes
// ========== ANDROID SPECIFIC ==========
notificationChannelId?: string; // Notification channel ID
foregroundNotificationTitle?: string; // Notification title
foregroundNotificationDescription?: string; // Notification text
// ========== BATTERY OPTIMIZATION ==========
batteryMode?: BatteryMode; // 'low'|'balanced'|'high' (default: 'balanced')
// ========== DATABASE ==========
maxQueueSize?: number; // Max queued records (default: 10000)
}await sdk.initialize({
apiKey: 'your-api-key',
uploadEndpoint: 'https://api.yourcompany.com/locations',
});await sdk.initialize({
apiKey: 'your-api-key',
uploadEndpoint: 'https://api.yourcompany.com/locations',
trackingInterval: 10000, // 10 seconds
distanceFilter: 20, // 20 meters
accuracy: 'high',
batteryMode: 'balanced',
enableBackgroundTracking: true,
enableOfflineSync: true,
enableBatteryOptimization: true,
});await sdk.initialize({
apiKey: 'your-api-key',
uploadEndpoint: 'https://api.yourcompany.com/locations',
trackingInterval: 5000, // 5 seconds
distanceFilter: 10, // 10 meters
accuracy: 'best',
batteryMode: 'high',
enableJourneyTracking: true,
enableGeofencing: true,
});await sdk.initialize({
apiKey: 'your-api-key',
uploadEndpoint: 'https://api.yourcompany.com/locations',
trackingInterval: 30000, // 30 seconds
distanceFilter: 50, // 50 meters
accuracy: 'medium',
batteryMode: 'low',
enableActivityRecognition: true,
enableBatteryOptimization: true,
});π Full Configuration Guide: docs/SETUP_GUIDE.md#sdk-configuration
| Document | Description |
|---|---|
| API Reference | Complete API documentation with all methods, types, and events |
| Setup Guide | Detailed platform setup, installation, and configuration |
| Usage Examples | Real-world code examples for all features |
| Troubleshooting | Common issues, solutions, and debugging tips |
| Contributing Guide | How to contribute to the SDK |
- π Quick Start - Get running in 5 minutes
- π¦ Installation - Install the SDK
- π οΈ Platform Setup - Platform-specific configuration
- βοΈ Configuration - SDK configuration options
- π Battery Optimization - Optimize for battery life
- π Backend Integration - Integrate with your backend
- π Troubleshooting - Fix common issues
- Version: 0.73.0 or higher
- New Architecture: Required (TurboModules)
- Hermes Engine: Recommended
- Minimum SDK: API Level 24 (Android 7.0)
- Target SDK: API Level 34 (Android 14)
- Google Play Services: Location 21.1.0+
- Kotlin: 1.9.0+
- Gradle: 8.0+
- Minimum Version: iOS 13.0
- Xcode: 15.0+
- Swift: 5.9+
- CocoaPods: 1.12.0+
- Node.js: 18.x or higher
- npm: 9+ or yarn 3+
- Android Studio: 2023.1.1 (Hedgehog) or later
- TypeScript: 5.0+ (recommended)
Track your vehicle fleet in real-time with journey analytics, geofencing for depot zones, and driver activity monitoring.
// Fleet tracking configuration
await sdk.initialize({
apiKey: 'fleet-api-key',
uploadEndpoint: 'https://fleet.company.com/vehicles',
employeeId: vehicleId,
trackingInterval: 10000,
enableJourneyTracking: true,
enableGeofencing: true,
});Monitor field employee locations for safety, efficiency, and compliance with clock-in/out geofences.
// Employee tracking with geofencing
await sdk.initialize({
apiKey: 'hr-api-key',
uploadEndpoint: 'https://hr.company.com/employees',
employeeId: employeeId,
enableGeofencing: true,
enableActivityRecognition: true,
});
// Add office geofence
await sdk.addGeofence({
type: 'circle',
center: { latitude: 37.7749, longitude: -122.4194 },
radius: 50,
metadata: { name: 'Office', autoClockIn: true },
});Optimize delivery routes, provide real-time ETAs, and automate proof of delivery with geofence detection.
// Delivery tracking
const journeyId = await sdk.startJourney({
purpose: 'delivery',
orderId: orderId,
customerId: customerId,
deliveryAddress: address,
});
// Add delivery location geofence
await sdk.addGeofence({
type: 'circle',
center: deliveryCoordinates,
radius: 30,
metadata: { orderId: orderId, autoComplete: true },
});Track technician locations, optimize dispatch, and verify on-site arrival/departure times.
// Field service tracking
await sdk.initialize({
apiKey: 'service-api-key',
uploadEndpoint: 'https://service.company.com/technicians',
employeeId: technicianId,
enableJourneyTracking: true,
enableGeofencing: true,
batteryMode: 'balanced',
});| Battery Mode | Update Interval | Distance Filter | Accuracy | Battery/24hrs | Use Case |
|---|---|---|---|---|---|
| Low | 30 seconds | 50 meters | Medium | 5-8% | Minimal tracking |
| Balanced | 10 seconds | 20 meters | High | 10-15% | Normal tracking (recommended) |
| High | 5 seconds | 10 meters | Best | 20-30% | High precision |
await sdk.initialize({
batteryMode: 'balanced',
enableBatteryOptimization: true,
});Automatically reduces GPS usage when user is stationary:
await sdk.initialize({
enableActivityRecognition: true,
enableBatteryOptimization: true,
});await sdk.initialize({
trackingInterval: 15000, // 15 seconds (less frequent)
distanceFilter: 30, // 30 meters (larger threshold)
accuracy: 'medium', // Lower accuracy = less power
});await sdk.initialize({
syncInterval: 300000, // Sync every 5 minutes
});sdk.addEventListener('batteryLow', (data) => {
console.log('Battery low:', data.level);
// Automatically switch to low battery mode
switchToLowPowerMode();
});π Complete Battery Guide: docs/USAGE_EXAMPLES.md#battery-optimization
Your backend should accept POST requests with this format:
Request:
POST /locations HTTP/1.1
Content-Type: application/json
Authorization: Bearer <token>
X-API-Key: <api-key>
{
"locations": [
{
"uuid": "550e8400-e29b-41d4-a716-446655440000",
"latitude": 37.7749,
"longitude": -122.4194,
"accuracy": 10.5,
"altitude": 15.2,
"bearing": 180.0,
"speed": 5.5,
"provider": "fused",
"isMock": false,
"timestamp": 1704067200000,
"employeeId": "EMP001"
}
],
"deviceInfo": {
"platform": "android",
"osVersion": "14",
"appVersion": "1.0.0"
}
}Response (Success):
{
"status": "success",
"received": 1
}Response (Error):
{
"status": "error",
"code": "INVALID_DATA",
"message": "Invalid location data"
}π Complete Backend Guide: docs/SETUP_GUIDE.md
| Issue | Cause | Solution |
|---|---|---|
| "SDK not initialized" | Called SDK method before initialize() |
Always call initialize() first and wait for promise |
| "Permission denied" | Location permissions not granted | Request all location permissions before initializing |
| No location updates | GPS disabled or permissions missing | Enable GPS and check permission status |
| High battery drain | Using best accuracy with 5s interval |
Use balanced mode, increase interval to 10-15s |
| Locations not syncing | Network error, backend down, auth failure | Check logs, verify endpoint URL and API key |
| Tracking stops in background | Android battery optimization | Request exemption in Settings β Battery β App |
| Foreground service not starting | Missing notification permission (Android 13+) | Request POST_NOTIFICATIONS permission |
# Monitor location updates
adb logcat -s LocationSDKModule LocationService
# Check foreground service status
adb shell dumpsys activity services | grep LocationService
# View database content
adb shell "run-as com.yourapp sqlite3 /data/data/com.yourapp/databases/location_sdk.db 'SELECT COUNT(*) FROM locations;'"
# Monitor sync operations
adb logcat | grep SyncManager// Add this to see all SDK events
const events = ['location', 'syncCompleted', 'syncFailed', 'error'];
events.forEach(event => {
sdk.addEventListener(event, (data) => {
console.log(`[SDK] ${event}:`, data);
});
});π Complete Troubleshooting Guide: docs/TROUBLESHOOTING.md
| Document | Description |
|---|---|
| π API Reference | Complete API documentation with all methods, types, events, and examples |
| π οΈ Setup Guide | Detailed platform setup, installation, configuration, and best practices |
| π‘ Usage Examples | Real-world code examples covering all SDK features |
| π Troubleshooting | Common issues, solutions, debugging tips, and FAQ |
| π€ Contributing | Guidelines for contributing to the SDK |
- π Quick Start - Get running in 5 minutes
- π¦ Installation - Install the SDK
- π οΈ Platform Setup - Configure Android/iOS
- βοΈ Configuration - SDK configuration options
- π» Basic Usage - Code examples
- π Battery Optimization - Optimize battery life
- π Backend Integration - API integration
- πΌ Use Cases - Real-world applications
Contributions are welcome! We appreciate bug reports, feature requests, documentation improvements, and code contributions.
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
# Clone repository
git clone https://github.com/NAWCREST-TECH-INNOVATION/nawcrest-react-native-location-sdk.git
cd nawcrest-react-native-location-sdk
# Install dependencies
yarn install
# Run example app
yarn example android
# Run tests
yarn test
# Lint code
yarn lint
# TypeScript check
yarn typecheck- Follow the existing code style and conventions
- Write tests for new features
- Update documentation for API changes
- Keep pull requests focused and small
- Write clear commit messages
π Full Contributing Guide: CONTRIBUTING.md
MIT License
Copyright (c) 2026 NAWCREST TECH INNOVATION
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED.
See LICENSE for full details.
- π Bug Reports: GitHub Issues
- π¬ Questions: GitHub Discussions
- π§ Email: nawcrest@gmail.com
- π Documentation: GitHub Wiki
- Check the Troubleshooting Guide
- Search existing issues
- Review the API Documentation
When reporting bugs, please include:
- SDK version
- React Native version
- Platform and OS version
- Steps to reproduce
- Expected vs actual behavior
- Relevant logs/screenshots
Built with these amazing open-source libraries:
- React Native - Cross-platform mobile framework
- Google Play Services Location - Fused location provider
- SQLCipher - Encrypted database
- WorkManager - Background task scheduling
- OkHttp - HTTP client
- Kotlin - Modern Android development
- TypeScript - Type-safe JavaScript
Special thanks to all our contributors!
- β Background location tracking with foreground service
- β Offline-first architecture with SQLCipher encryption
- β Journey tracking with complete analytics
- β Circular and polygon geofencing
- β Activity recognition for battery optimization
- β Auto-sync with exponential backoff retry
- β Remote location requests via FCM
- β React Native New Architecture (TurboModules)
- β Comprehensive TypeScript definitions
- β Production-ready documentation
- iOS native implementation
- Background location tracking (significant changes)
- Region monitoring for geofencing
- Journey tracking with Core Location
- Activity recognition with Core Motion
- Offline queue with Core Data
- Cross-platform feature parity
- Unified API for Android and iOS
- Advanced battery optimization algorithms
- Real-time location streaming via WebSocket
- Route prediction with machine learning
- Improved geofence analytics
- Location accuracy verification
- Enhanced mock location detection
- Configurable data retention policies
- Multi-user/multi-device tracking
- Offline map caching
- Advanced route optimization
- Historical playback and visualization
- Custom event triggers
- Enhanced analytics and reporting
- Cloud configuration management
Vote on features: GitHub Discussions
If this SDK helps your project, please:
- β Star the repository on GitHub
- π¦ Share on social media
- π Write a blog post or tutorial
- π€ Contribute code, docs, or bug reports
- π¬ Join our discussions
Your support helps us maintain and improve the SDK!
Made with β€οΈ by NAWCREST TECH INNOVATION
Website β’ GitHub β’ npm β’ Documentation