Convert Figma logo to code with AI

Agontuk logoreact-native-geolocation-service

React native geolocation service for iOS and android

1,628
293
1,628
129

Top Related Projects

Geolocation APIs for React Native

Sophisticated, battery-conscious background-geolocation with motion-detection

Quick Overview

React Native Geolocation Service is a library that provides geolocation support for React Native applications on both Android and iOS platforms. It offers a more reliable and accurate alternative to the core Geolocation API, with additional features and improved performance.

Pros

  • More reliable and accurate than the core Geolocation API
  • Supports both Android and iOS platforms
  • Provides additional features like background location updates and geocoding
  • Actively maintained and regularly updated

Cons

  • Requires additional setup and configuration compared to the core API
  • May increase app size due to additional dependencies
  • Some features may require extra permissions, potentially affecting user privacy concerns
  • Limited documentation for advanced use cases

Code Examples

  1. Getting the current position:
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 }
);
  1. Watching position changes:
const watchId = Geolocation.watchPosition(
    (position) => {
        console.log(position);
    },
    (error) => {
        console.log(error.code, error.message);
    },
    { enableHighAccuracy: true, distanceFilter: 10, interval: 5000, fastestInterval: 2000 }
);
  1. Clearing a watch:
Geolocation.clearWatch(watchId);

Getting Started

  1. Install the library:

    npm install react-native-geolocation-service
    
  2. For iOS, add the following to your Info.plist:

    <key>NSLocationWhenInUseUsageDescription</key>
    <string>This app needs access to location when open.</string>
    
  3. For Android, add the following permission to your AndroidManifest.xml:

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    
  4. Import and use the library in your React Native code:

    import Geolocation from 'react-native-geolocation-service';
    
    // Use Geolocation methods as shown in the code examples above
    

Remember to handle permissions appropriately in your app before using geolocation features.

Competitor Comparisons

Geolocation APIs for React Native

Pros of react-native-geolocation

  • Simpler API with fewer methods, making it easier to use for basic geolocation tasks
  • Maintained as part of the React Native core, ensuring better compatibility with React Native updates
  • Smaller package size, potentially reducing app bundle size

Cons of react-native-geolocation

  • Less frequent updates compared to react-native-geolocation-service
  • Fewer advanced features, such as custom location providers or background location tracking
  • Limited configuration options for fine-tuning geolocation behavior

Code Comparison

react-native-geolocation:

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

Geolocation.getCurrentPosition(
  position => console.log(position),
  error => console.log(error),
  { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 }
);

react-native-geolocation-service:

import Geolocation from 'react-native-geolocation-service';

Geolocation.getCurrentPosition(
  position => console.log(position),
  error => console.log(error),
  { enableHighAccuracy: true, timeout: 15000, maximumAge: 10000, distanceFilter: 0 }
);

Both libraries offer similar basic functionality, but react-native-geolocation-service provides more configuration options and advanced features for complex geolocation requirements.

Sophisticated, battery-conscious background-geolocation with motion-detection

Pros of react-native-background-geolocation

  • Supports background location tracking, allowing continuous location updates even when the app is not in the foreground
  • Offers advanced features like geofencing, motion detection, and trip detection
  • Provides more comprehensive documentation and examples

Cons of react-native-background-geolocation

  • Requires a paid license for production use, which may be a barrier for some developers
  • Has a larger footprint and may impact app size more significantly
  • More complex setup and configuration process compared to simpler alternatives

Code Comparison

react-native-geolocation-service:

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 }
);

react-native-background-geolocation:

import BackgroundGeolocation from "react-native-background-geolocation";

BackgroundGeolocation.ready({
  desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_HIGH,
  distanceFilter: 10,
  stopOnTerminate: false,
  startOnBoot: true,
}, (state) => {
  console.log("- BackgroundGeolocation is ready: ", state);
});

Both libraries provide geolocation functionality, but react-native-background-geolocation offers more advanced features and background tracking capabilities at the cost of increased complexity and licensing fees. The choice between them depends on the specific requirements of your project and budget constraints.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

react-native-geolocation-service

React native geolocation service for iOS and android.

Why ?

This library is created in an attempt to fix the location timeout issue on android with the react-native's current implementation of Geolocation API. This library tries to solve the issue by using Google Play Service's new FusedLocationProviderClient API, which Google strongly recommends over android's default framework location API. It automatically decides which provider to use based on your request configuration and also prompts you to change the location mode if it doesn't satisfy your current request configuration.

NOTE: Location request can still timeout since many android devices have GPS issue in the hardware/system level. Check the FAQ for more details.

Installation

yarn

yarn add react-native-geolocation-service

npm

npm install react-native-geolocation-service

Compatibility

RN VersionPackage Version
>=0.60>=3.0.0
<0.602.0.0
<0.571.1.0

Setup

Usage

Since this library was meant to be a drop-in replacement for the RN's Geolocation API, the usage is pretty straight forward, with some extra error cases to handle.

One thing to note, for android this library assumes that location permission is already granted by the user, so you have to use PermissionsAndroid to request for permission before making the location request.

...
import Geolocation from 'react-native-geolocation-service';
...

componentDidMount() {
  if (hasLocationPermission) {
    Geolocation.getCurrentPosition(
        (position) => {
          console.log(position);
        },
        (error) => {
          // See error code charts below.
          console.log(error.code, error.message);
        },
        { enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 }
    );
  }
}

API

async requestAuthorization(authorizationLevel) (iOS only)

Request location permission based on the authorizationLevel parameter. Can be either "whenInUse" or "always". You have to configure the plist keys during setup.

When promise resolves, returns the status of the authorization.

  • disabled - Location service is disabled
  • granted - Permission granted
  • denied - Permission denied
  • restricted - Permission restricted

getCurrentPosition(successCallback, ?errorCallback, ?options)

  • successCallback: Invoked with latest location info.

  • errorCallback: Invoked whenever an error is encountered.

  • options:

    NameTypeDefaultDescription
    timeoutmsINFINITYRequest timeout
    maximumAgemsINFINITYHow long previous location will be cached
    accuracyobject--{
       android: Link,
       ios: Link
    }

    If not provided or provided with invalid value, falls back to use enableHighAccuracy
    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 set to true, will use android's default LocationManager API (android only)

watchPosition(successCallback, ?errorCallback, ?options)

  • successCallback: Invoked with latest location info.

  • errorCallback: Invoked whenever an error is encountered.

  • options:

    NameTypeDefaultDescription
    accuracyobject--{
       android: Link,
       ios: Link
    }

    If not provided or provided with invalid value, falls back to use enableHighAccuracy
    enableHighAccuracyboolfalseUse high accuracy mode
    distanceFilterm100Minimum displacement between location updates in meters
    intervalms10000Interval for active location updates (android only)
    fastestIntervalms5000Fastest rate at which your application will receive location updates, which might be faster than interval in some situations (for example, if other applications are triggering location 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 set to true, will use android's default LocationManager API (android only)
    useSignificantChangesboolfalseUses the battery-efficient native significant changes APIs to return locations. Locations will only be returned when the device detects a significant distance has been breached (iOS only)
    showsBackgroundLocationIndicatorboolfalseThis setting enables a blue bar or a blue pill in the status bar on iOS. When the app moves to the background, the system uses this property to determine whether to change the status bar appearance to indicate that location services are in use. Users can tap the indicator to return to your app. (iOS only)

clearWatch(watchId)

  • watchId (id returned by watchPosition)

stopObserving()

Stops observing for device location changes. In addition, it removes all listeners previously registered.

Error Codes

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 for the current request (android only)
INTERNAL_ERROR-1Library crashed for some reason or the getCurrentActivity() returned null (android only)

FAQ

  1. Location timeout still happening ?

    Try the following steps: (Taken from here)

    • Turn phone off/on
    • Turn GPS off/on
    • Disable any battery saver settings, including Power Saving Mode, Battery Management or any third party apps
    • Perform an "AGPS reset": Install the App GPS Status & Toolbox, then in that app, go to Menu > Tools > Manage A-GPS State > Reset

    Adjusting battery saver settings on different devices:

    • HTC: Access your phone settings > battery > power saving mode > battery optimization > select your app > don't optimize > save
    • Huawei: Turn Energy Settings to Normal and add your app to "Protected Apps"
    • LG If you're running Android 6 or higher: Settings > battery & power saving > battery usage > ignore optimizations > turn ON for your app
    • Motorola If you're running Android 6 or higher: Battery > select the menu in the upper right-hand corner > battery optimization > not optimized > all apps > select your app > don't optimize
    • OnePlus (using OxygenOS Settings): Battery > battery optimization > switch to 'all apps' > select your app > don't optimize
    • Samsung: Access battery settings > app power saving > details > your app > disabled
    • Sony If you're running Android 6 or higher: Battery > from the menu in the upper right-hand corner > battery optimization > apps > your app
    • Xiaomi (MIUI OS) If you're running Android 6 or higher: Access your phone settings > additional settings > battery and performance > manage battery usage > apps > your app