react-native-geolocation-service

repository·master·Indexed 23 days ago

https://github.com/agontuk/react-native-geolocation-service

A React Native geolocation service for iOS and Android. It serves as a drop-in replacement for the React Native Geolocation API and utilizes Google Play Services' FusedLocationProviderClient on Android to resolve common location timeout issues. The library provides methods for retrieving the current position, watching location updates, and managing location permissions.

Tokens
3.6K
Snippets
8
Records
15
Agent score
82%

What's inside react-native-geolocation-service

  1. Setup iOS for react-native-geolocation-service

    master

    Follow these steps to configure the library for iOS projects.

    1) Linking

    For React Native 0.60 or higher, manual linking is not required. After installing the package, run pod install from the ios directory to automatically pick up the package.

    For RN 0.59 or below:

    • Using Cocoapods: Update your Podfile with:
      pod 'react-native-geolocation-service', path: '../node_modules/react-native-geolocation-service'
      Then run pod install from the ios directory.
    • Manual Linking: Drag RNFusedLocation.xcodeproj into your Xcode project (e.g., under the Libraries group) and add the libRNFusedLocation.a binary to your project's Build Phases -> Link Binary With Libraries section.

    2) Enable Swift Support

    The iOS implementation is written in Swift. You must add Swift support to your project via Xcode:

    1. Select File -> New -> File in Xcode.
    2. Choose a Swift file and name it anything.
    3. When prompted, click Yes to generate a bridging header. This is required to update the Swift compiler flags.

    3) Update info.plist

    Add the required location usage descriptions to your info.plist.

    • Standard usage: Add NSLocationWhenInUseUsageDescription.
    • Background location usage: You must add all three keys below AND enable 'location' as a background mode in the Signing & Capabilities -> Capability tab in Xcode:
      • NSLocationWhenInUseUsageDescription
      • NSLocationAlwaysUsageDescription
      • NSLocationAlwaysAndWhenInUseUsageDescription
    pod 'react-native-geolocation-service', path: '../node_modules/react-native-geolocation-service'
  2. Setup Android for react-native-geolocation-service

    master

    Follow these steps to configure the library for Android projects.

    1) Linking

    For React Native 0.60 or higher, manual linking is not required. You can override Google Play Services versions in your root build.gradle file.

    For RN 0.59 or below:

    1. In android/app/build.gradle, add the implementation:
      dependencies {
          implementation project(':react-native-geolocation-service')
      }
      Note: If you use project-wide properties in your root build.gradle, the library will automatically detect them. If you need a specific Play Services version different from the library default, use an exclude block as shown in the reference below.
    2. In android/settings.gradle, include the project:
      include ':react-native-geolocation-service'
      project(':react-native-geolocation-service').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-geolocation-service/android')
    3. In MainApplication.java, register the package:
      import com.agontuk.RNFusedLocation.RNFusedLocationPackage;
      // ... inside getPackages()
      new RNFusedLocationPackage()

    2) Permissions

    Add the following permissions to your AndroidManifest.xml based on your requirements:

    • android.permission.ACCESS_COARSE_LOCATION
    • android.permission.ACCESS_FINE_LOCATION
    ext {
      compileSdkVersion   = 28
      buildToolsVersion   = "28.0.3"
      minSdkVersion       = 16
      targetSdkVersion    = 28
    
      googlePlayServicesVersion      = "17.0.0"
    }
  3. How to use react-native-geolocation-service

    master

    The library is designed as a drop-in replacement for the React Native Geolocation API.

    Important for Android: This library assumes location permission is already granted. You must use PermissionsAndroid to request permissions before calling any location methods.

    Example Usage:

    import Geolocation from 'react-native-geolocation-service';
    
    // Inside a component or function
    Geolocation.getCurrentPosition(
        (position) => {
          console.log(position);
        },
        (error) => {
          // Handle error (see Error Codes section)
          console.log(error.code, error.message);
        },
        { enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 }
    );
    import Geolocation from 'react-native-geolocation-service';
    
    Geolocation.getCurrentPosition(
        (position) => {
          console.log(position);
        },
        (error) => {
          console.log(error.code, error.message);
        },
        { enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 }
    );
  4. getCurrentPosition(successCallback, errorCallback, options)

    master

    Invokes the callback with the latest location information.

    Parameters:

    • successCallback: Function invoked with latest location info.
    • errorCallback: Function invoked whenever an error is encountered.
    • options: Configuration object.

    Options Reference:

    NameTypeDefaultDescription
    timeoutmsINFINITYRequest timeout
    maximumAgemsINFINITYHow long previous location will be cached
    accuracyobject--{ android: ..., ios: ... }. Falls back to enableHighAccuracy if invalid
    enableHighAccuracyboolfalseUse high accuracy mode
    distanceFilterm100Minimum displacement in meters
    showLocationDialogbooltrueWhether to ask to enable location in Android (android only)
    forceRequestLocationboolfalseForce request location even after denying improve accuracy dialog (android only)
    forceLocationManagerboolfalseIf true, uses android's default LocationManager API (android only)
  5. requestAuthorization(authorizationLevel) (iOS only)

    master

    Requests location permission on iOS. The authorizationLevel can be either "whenInUse" or "always". You must configure the corresponding plist keys during setup.

    Returns a Promise that resolves to the authorization status:

    • disabled: Location service is disabled
    • granted: Permission granted
    • denied: Permission denied
    • restricted: Permission restricted
  6. watchPosition(successCallback, errorCallback, options)

    master

    Subscribes to location updates.

    Parameters:

    • successCallback: Function invoked with latest location info.
    • errorCallback: Function invoked whenever an error is encountered.
    • options: Configuration object.

    Options Reference:

    NameTypeDefaultDescription
    accuracyobject--{ android: ..., ios: ... }. Falls back to enableHighAccuracy
    enableHighAccuracyboolfalseUse high accuracy mode
    distanceFilterm100Minimum displacement between updates in meters
    intervalms10000Interval for active location updates (android only)
    fastestIntervalms5000Fastest rate for updates (android only)
    showLocationDialogbooltrueWhether to ask to enable location in Android (android only)
    forceRequestLocationboolfalseForce request location even after denying improve accuracy dialog (android only)
    forceLocationManagerboolfalseIf true, uses android's default LocationManager API (android only)
    useSignificantChangesboolfalseUses battery-efficient native significant changes APIs (iOS only)
    showsBackgroundLocationIndicatorboolfalseEnables blue bar/pill in status bar when app is in background (iOS only)
  7. Understand Android accuracy levels

    master

    When requesting location updates on Android, you can specify an accuracy level. These levels correspond to Google Play Services LocationRequest constants:

    • high: Returns the finest location available.
    • balanced: Provides block-level accuracy (approximately 100 meters).
    • low: Provides city-level accuracy (approximately 10km).
    • passive: Does not request location updates itself; instead, it acts as a passive listener to location updates requested by other clients on the device.
    | Name | Description |
    | -- | -- |
    | high | This will return the finest location available. |
    | balanced | Block level accuracy considered to be about 100 meter accuracy. |
    | low | City level accuracy is considered to be about 10km accuracy. |
    | passive | No locations will be returned unless a different client has requested location updates in which case this request will act as a passive listener to those locations. |
  8. Understand iOS accuracy levels

    master

    When requesting location updates on iOS, you can specify an accuracy level. These levels correspond to Apple's CLLocationAccuracy constants:

    • bestForNavigation: The highest possible accuracy, utilizing additional sensor data for navigation apps.
    • best: The best level of accuracy available.
    • nearestTenMeters: Accurate to within ten meters of the target.
    • hundredMeters: Accurate to within one hundred meters.
    • kilometer: Accurate to the nearest kilometer.
    • threeKilometers: Accurate to the nearest three kilometers.
    • reduced: Used when the application does not require accurate location data.
    | Name | Description |
    | -- | -- |
    | bestForNavigation | The highest possible accuracy that uses additional sensor data to facilitate navigation apps. |
    | best | The best level of accuracy available. |
    | nearestTenMeters | Accurate to within ten meters of the desired target. |
    | hundredMeters | Accurate to within one hundred meters. |
    | kilometer | Accurate to the nearest kilometer. |
    | threeKilometers | Accurate to the nearest three kilometers. |
    | reduced | Used when an app does not need accurate location data. |
  9. Error Codes Reference

    master

    When the errorCallback is triggered, the error object contains a code and a message. Use these codes to handle specific failure scenarios.

    NameCodeDescription
    PERMISSION_DENIED1Location permission is not granted
    POSITION_UNAVAILABLE2Location provider not available
    TIMEOUT3Location request timed out
    PLAY_SERVICE_NOT_AVAILABLE4Google play service is not installed or has an older version (android only)
    SETTINGS_NOT_SATISFIED5Location service is not enabled or location mode is not appropriate (android only)
    INTERNAL_ERROR-1Library crashed or getCurrentActivity() returned null (android only)
  10. Reference: Android Gradle configuration and Permissions

    master

    When configuring Android, you may need to manage Play Services versions or declare permissions in AndroidManifest.xml.

    // Gradle property overrides
    ext {
      compileSdkVersion   = 28
      buildToolsVersion   = "28.0.3"
      minSdkVersion       = 16
      targetSdkVersion    = 28
    
      // Any of the following will work
      googlePlayServicesVersion      = "17.0.0"
      // playServicesVersion         = "17.0.0"
      // playServicesLocationVersion = "17.0.0"
    }
    
    // Manual dependency management for RN < 0.60 with specific Play Services version
    dependencies {
        implementation(project(':react-native-geolocation-service')) {
            exclude group: 'com.google.android.gms', module: 'play-services-location'
        }
        implementation 'com.google.android.gms:play-services-location:<insert your play service version here>'
    }
    <!-- AndroidManifest.xml permissions -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />