Try Live
Add Docs
Rankings
Pricing
Docs
Install
Theme
Install
Docs
Pricing
More...
More...
Try Live
Rankings
Enterprise
Create API Key
Add Docs
React Native Geolocation Service
https://github.com/agontuk/react-native-geolocation-service
Admin
A React Native library for iOS and Android that provides a robust geolocation service, aiming to fix
...
Tokens:
8,874
Snippets:
48
Trust Score:
8.9
Update:
4 months ago
Context
Skills
Chat
Benchmark
94
Suggestions
Latest
Show doc for...
Code
Info
Show Results
Context Summary (auto-generated)
Raw
Copy
Link
# react-native-geolocation-service ## Introduction react-native-geolocation-service is a React Native library that provides geolocation services for iOS and Android applications. The library was created to address location timeout issues on Android by leveraging Google Play Services' FusedLocationProviderClient API instead of Android's default framework location API. This approach allows the system to intelligently select the best location provider based on request configuration and prompts users to adjust location settings when necessary. The library serves as a drop-in replacement for React Native's built-in Geolocation API, offering the same interface with enhanced reliability and additional platform-specific features. It supports both one-time location requests and continuous location tracking, with configurable accuracy levels, timeout settings, and battery-efficient options. For iOS, it provides Swift-based implementation with support for authorization levels and significant location changes, while Android users benefit from integration with Google Play Services and automatic location provider selection. ## API Documentation ### getCurrentPosition - One-time Location Request Retrieves the device's current location with configurable accuracy and timeout settings. The function accepts success and error callbacks along with optional configuration parameters for fine-tuning the location request behavior. ```javascript import Geolocation from 'react-native-geolocation-service'; import { PermissionsAndroid, Platform } from 'react-native'; // Request permission (Android) async function requestLocationPermission() { if (Platform.OS === 'android') { const granted = await PermissionsAndroid.request( PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION, { title: 'Location Permission', message: 'This app needs access to your location', buttonNeutral: 'Ask Me Later', buttonNegative: 'Cancel', buttonPositive: 'OK', } ); return granted === PermissionsAndroid.RESULTS.GRANTED; } return true; } // Get current position async function getLocation() { const hasPermission = await requestLocationPermission(); if (hasPermission) { Geolocation.getCurrentPosition( (position) => { console.log('Location:', { latitude: position.coords.latitude, longitude: position.coords.longitude, accuracy: position.coords.accuracy, altitude: position.coords.altitude, heading: position.coords.heading, speed: position.coords.speed, timestamp: position.timestamp, provider: position.provider // 'fused', 'gps', 'network', or 'passive' }); }, (error) => { console.error('Location Error:', error.code, error.message); // Error codes: 1=PERMISSION_DENIED, 2=POSITION_UNAVAILABLE, // 3=TIMEOUT, 4=PLAY_SERVICE_NOT_AVAILABLE, 5=SETTINGS_NOT_SATISFIED }, { enableHighAccuracy: true, timeout: 15000, maximumAge: 10000, distanceFilter: 0, forceRequestLocation: true, showLocationDialog: true } ); } } ``` ### watchPosition - Continuous Location Tracking Monitors device location changes and triggers callbacks when the device moves beyond a specified distance threshold or time interval. Returns a watch ID that can be used to stop tracking. ```javascript import Geolocation from 'react-native-geolocation-service'; let watchId = null; // Start watching location function startLocationTracking() { watchId = Geolocation.watchPosition( (position) => { console.log('Location Update:', { latitude: position.coords.latitude, longitude: position.coords.longitude, accuracy: position.coords.accuracy, speed: position.coords.speed, heading: position.coords.heading, timestamp: new Date(position.timestamp).toISOString(), mocked: position.mocked // Indicates if location is from mock provider }); }, (error) => { console.error('Watch Error:', error.code, error.message); if (error.code === 5) { console.error('Location settings not satisfied'); } }, { accuracy: { android: 'high', ios: 'best' }, enableHighAccuracy: true, distanceFilter: 10, // Update every 10 meters interval: 5000, // Android: Check every 5 seconds fastestInterval: 2000, // Android: Fastest update rate showLocationDialog: true, forceRequestLocation: false, useSignificantChanges: false // iOS: Use significant change monitoring } ); console.log('Started tracking with watchId:', watchId); } // Stop watching location function stopLocationTracking() { if (watchId !== null) { Geolocation.clearWatch(watchId); console.log('Stopped tracking'); watchId = null; } } // Stop all location updates function stopAllTracking() { Geolocation.stopObserving(); watchId = null; console.log('Stopped all location observers'); } ``` ### requestAuthorization - iOS Location Permission Requests location permission on iOS with support for "whenInUse" or "always" authorization levels. Returns a promise that resolves with the authorization status. ```javascript import Geolocation from 'react-native-geolocation-service'; import { Platform } from 'react-native'; // Request iOS authorization async function requestiOSAuthorization() { if (Platform.OS !== 'ios') { console.log('This method is iOS only'); return; } try { // Request "whenInUse" authorization const authStatus = await Geolocation.requestAuthorization('whenInUse'); console.log('Authorization status:', authStatus); // Possible values: 'disabled', 'granted', 'denied', 'restricted' switch (authStatus) { case 'granted': console.log('Location permission granted'); // Proceed with location requests break; case 'denied': console.log('Location permission denied by user'); break; case 'disabled': console.log('Location services are disabled'); break; case 'restricted': console.log('Location permission restricted (parental controls)'); break; } return authStatus; } catch (error) { console.error('Authorization error:', error); } } // Request always authorization (for background tracking) async function requestAlwaysAuthorization() { if (Platform.OS !== 'ios') { return; } try { const authStatus = await Geolocation.requestAuthorization('always'); if (authStatus === 'granted') { console.log('Always authorization granted'); // Can now track location in background } return authStatus; } catch (error) { console.error('Always authorization error:', error); } } ``` ### Platform-Specific Accuracy Configuration Configure location accuracy separately for Android and iOS platforms using platform-specific accuracy enumerations for optimal battery and precision balance. ```javascript import Geolocation from 'react-native-geolocation-service'; // High accuracy configuration (GPS + Network) function getHighAccuracyLocation() { Geolocation.getCurrentPosition( (position) => { console.log('High accuracy position:', position.coords); }, (error) => { console.error('Error:', error); }, { accuracy: { android: 'high', // Finest location available ios: 'best' // Best level of accuracy }, timeout: 20000, maximumAge: 0, distanceFilter: 0 } ); } // Balanced accuracy configuration (Battery-efficient) function getBalancedLocation() { Geolocation.getCurrentPosition( (position) => { console.log('Balanced accuracy position:', position.coords); }, (error) => { console.error('Error:', error); }, { accuracy: { android: 'balanced', // ~100 meter accuracy ios: 'hundredMeters' // 100 meter accuracy }, timeout: 15000, maximumAge: 60000 } ); } // Low accuracy configuration (City-level) function getLowAccuracyLocation() { Geolocation.getCurrentPosition( (position) => { console.log('Low accuracy position:', position.coords); }, (error) => { console.error('Error:', error); }, { accuracy: { android: 'low', // ~10km accuracy ios: 'threeKilometers' // 3km accuracy }, timeout: 10000, maximumAge: 300000 } ); } // Navigation-grade accuracy (iOS) function getNavigationAccuracy() { Geolocation.getCurrentPosition( (position) => { console.log('Navigation position:', position.coords); }, (error) => { console.error('Error:', error); }, { accuracy: { android: 'high', ios: 'bestForNavigation' // Uses additional sensors }, enableHighAccuracy: true, distanceFilter: 5, timeout: 20000 } ); } ``` ### Error Handling and Error Codes Comprehensive error handling using standardized error codes for debugging location request failures across different scenarios. ```javascript import Geolocation, { PositionError } from 'react-native-geolocation-service'; function getLocationWithErrorHandling() { Geolocation.getCurrentPosition( (position) => { console.log('Success:', position); }, (error) => { switch (error.code) { case PositionError.PERMISSION_DENIED: console.error('Permission denied - User denied location permission'); // Prompt user to enable location permission in settings break; case PositionError.POSITION_UNAVAILABLE: console.error('Position unavailable - Location provider not available'); // Check if GPS is enabled break; case PositionError.TIMEOUT: console.error('Timeout - Location request timed out'); // Try again with higher timeout or lower accuracy break; case PositionError.PLAY_SERVICE_NOT_AVAILABLE: console.error('Play Services not available or outdated (Android only)'); // Prompt user to update Google Play Services break; case PositionError.SETTINGS_NOT_SATISFIED: console.error('Location settings not satisfied (Android only)'); // Location service disabled or mode inappropriate break; case PositionError.INTERNAL_ERROR: console.error('Internal error - Library error (Android only)'); break; default: console.error('Unknown error:', error.code, error.message); } }, { enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 } ); } // Error recovery example async function getLocationWithRetry(maxRetries = 3) { for (let attempt = 1; attempt <= maxRetries; attempt++) { try { await new Promise((resolve, reject) => { Geolocation.getCurrentPosition( resolve, reject, { enableHighAccuracy: attempt === 1, timeout: 10000 * attempt, maximumAge: attempt > 1 ? 60000 : 0 } ); }); return; // Success } catch (error) { console.log(`Attempt ${attempt} failed:`, error.message); if (error.code === PositionError.PERMISSION_DENIED) { console.error('Cannot retry - permission denied'); break; } if (attempt === maxRetries) { console.error('All retry attempts failed'); } } } } ``` ### Background Location Tracking (iOS) Enable background location updates on iOS with visual indicators and significant change monitoring for battery-efficient tracking. ```javascript import Geolocation from 'react-native-geolocation-service'; import { Platform } from 'react-native'; let backgroundWatchId = null; // Enable background tracking with status bar indicator function startBackgroundTracking() { if (Platform.OS !== 'ios') { console.log('Background options are iOS specific'); return; } backgroundWatchId = Geolocation.watchPosition( (position) => { console.log('Background location:', position.coords); // Send to server or update local database }, (error) => { console.error('Background tracking error:', error); }, { accuracy: { ios: 'best' }, distanceFilter: 50, showsBackgroundLocationIndicator: true, // Show blue bar/pill in status bar useSignificantChanges: false // Set true for battery-efficient mode } ); } // Battery-efficient background tracking function startSignificantChangeTracking() { if (Platform.OS !== 'ios') { return; } backgroundWatchId = Geolocation.watchPosition( (position) => { console.log('Significant location change:', position.coords); // Only triggers on significant distance changes (~500m) }, (error) => { console.error('Error:', error); }, { accuracy: { ios: 'best' }, useSignificantChanges: true, // Battery-efficient monitoring showsBackgroundLocationIndicator: true } ); } ``` ### Android-Specific Options Configure Android-specific location settings including location dialog prompts, force location requests, and choosing between Fused Location Provider and Location Manager. ```javascript import Geolocation from 'react-native-geolocation-service'; import { Platform } from 'react-native'; // Show location settings dialog function getLocationWithDialog() { if (Platform.OS !== 'android') { return; } Geolocation.getCurrentPosition( (position) => { console.log('Position:', position); }, (error) => { console.error('Error:', error); }, { enableHighAccuracy: true, timeout: 15000, showLocationDialog: true, // Ask user to enable location if disabled forceRequestLocation: false // Don't force after dialog denial } ); } // Force location request even after dialog denial function forceLocationRequest() { if (Platform.OS !== 'android') { return; } Geolocation.getCurrentPosition( (position) => { console.log('Forced position:', position); }, (error) => { console.error('Error:', error); }, { enableHighAccuracy: true, timeout: 20000, showLocationDialog: true, forceRequestLocation: true // Request location even if user denies dialog } ); } // Use legacy LocationManager instead of FusedLocationProviderClient function useLocationManager() { if (Platform.OS !== 'android') { return; } Geolocation.getCurrentPosition( (position) => { console.log('LocationManager position:', position); }, (error) => { console.error('Error:', error); }, { enableHighAccuracy: true, timeout: 15000, forceLocationManager: true // Use Android's default LocationManager API } ); } // Watch position with Android-specific intervals function watchWithIntervals() { if (Platform.OS !== 'android') { return; } const watchId = Geolocation.watchPosition( (position) => { console.log('Interval update:', position); }, (error) => { console.error('Error:', error); }, { accuracy: { android: 'balanced' }, interval: 10000, // Request updates every 10 seconds fastestInterval: 5000, // Accept updates as fast as 5 seconds distanceFilter: 20 // Or when moved 20 meters } ); return watchId; } ``` ## Summary react-native-geolocation-service is designed for React Native applications requiring reliable location services across iOS and Android platforms. The primary use cases include mapping applications, delivery tracking, fitness apps, location-based social features, and any application needing real-time or periodic location updates. The library excels in scenarios where location accuracy and reliability are critical, offering fine-grained control over accuracy levels, update intervals, and battery consumption through platform-specific configuration options. The library integrates seamlessly into React Native projects as a drop-in replacement for the built-in Geolocation API, requiring minimal code changes for migration. Developers can leverage platform-specific features such as iOS background location indicators and significant change monitoring, or Android's Fused Location Provider with customizable update intervals and location dialog prompts. The comprehensive error handling system, including specific error codes for Play Services availability and location settings satisfaction, enables robust error recovery strategies. For production applications, the library supports both foreground and background location tracking with appropriate permission handling, making it suitable for enterprise-grade location-based services.