Convert Figma logo to code with AI

michalchudziak logoreact-native-geolocation

Geolocation APIs for React Native

1,372
239
1,372
162

Top Related Projects

React native geolocation service for iOS and android

React Native Mapview component for iOS + Android

Geolocation APIs for React Native

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

Quick Overview

The react-native-geolocation library is a React Native module that provides access to the device's location services, allowing developers to retrieve the user's current location, monitor location changes, and more. It is a wrapper around the native iOS and Android location APIs, providing a consistent and easy-to-use interface for working with location data in React Native applications.

Pros

  • Cross-Platform Compatibility: The library supports both iOS and Android platforms, making it easy to build location-based features that work across multiple mobile operating systems.
  • Comprehensive API: The library provides a wide range of functionality, including the ability to get the current location, monitor location changes, and control the accuracy and frequency of location updates.
  • Active Development and Community: The project is actively maintained, with regular updates and a responsive community of contributors.
  • Reliable and Stable: The library is widely used and has a proven track record of reliability and stability.

Cons

  • Dependency on Native APIs: The library relies on the underlying native location APIs, which can sometimes have platform-specific quirks or limitations.
  • Potential Battery Drain: Frequent location updates can have a significant impact on battery life, so developers need to carefully manage the use of the library to minimize power consumption.
  • Limited Offline Functionality: The library is primarily designed for real-time location tracking, and may not provide robust offline functionality for scenarios where the device is disconnected from the network.
  • Lack of Advanced Features: While the library provides a solid set of basic location-related features, it may not offer more advanced functionality, such as geofencing or location-based notifications.

Code Examples

Retrieving the Current Location

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

Geolocation.getCurrentPosition(
  (position) => {
    console.log(position.coords.latitude, position.coords.longitude);
  },
  (error) => {
    console.log(error.code, error.message);
  },
  { enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 }
);

This code snippet demonstrates how to use the react-native-geolocation-service library to retrieve the user's current location.

Monitoring Location Changes

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

const watchId = Geolocation.watchPosition(
  (position) => {
    console.log(position.coords.latitude, position.coords.longitude);
  },
  (error) => {
    console.log(error.code, error.message);
  },
  {
    enableHighAccuracy: true,
    distanceFilter: 100,
    interval: 5000,
    fastestInterval: 2000,
  }
);

// Stop monitoring location changes
Geolocation.clearWatch(watchId);

This code snippet demonstrates how to use the react-native-geolocation-service library to monitor the user's location changes and stop the monitoring when it's no longer needed.

Requesting Location Permissions

import Geolocation from 'react-native-geolocation-service';
import { PermissionsAndroid } from 'react-native';

async function requestLocationPermission() {
  try {
    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',
      }
    );
    if (granted === PermissionsAndroid.RESULTS.GRANTED) {
      console.log('Location permission granted');
    } else {
      console.log('Location permission denied');
    }
  } catch (err) {
    console.warn(err);
  }
}

This code snippet demonstrates how to use the react-native-geolocation-service library to request location permissions on Android devices.

Getting Started

To get started with the react-native-geolocation library, follow these steps:

Competitor Comparisons

React native geolocation service for iOS and android

Pros of react-native-geolocation-service

  • Provides a more comprehensive set of geolocation-related features, including support for location permissions, background location updates, and geocoding.
  • Offers a more modern and streamlined API compared to the older react-native-geolocation library.
  • Supports both iOS and Android platforms with a consistent API.

Cons of react-native-geolocation-service

  • May have a steeper learning curve for developers who are already familiar with the older react-native-geolocation library.
  • Requires additional configuration and setup, such as setting up location permissions in the app's manifest files.
  • May have a larger footprint in the app's codebase compared to the simpler react-native-geolocation library.

Code Comparison

react-native-geolocation

import { getCurrentPosition, watchPosition } from 'react-native-geolocation';

getCurrentPosition((position) => {
  console.log(position.coords.latitude, position.coords.longitude);
});

watchPosition((position) => {
  console.log(position.coords.latitude, position.coords.longitude);
});

react-native-geolocation-service

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

Geolocation.getCurrentPosition(
  (position) => {
    console.log(position.coords.latitude, position.coords.longitude);
  },
  (error) => {
    console.log(error.code, error.message);
  },
  { enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 }
);

React Native Mapview component for iOS + Android

Pros of react-native-maps

  • Provides a comprehensive set of features for displaying and interacting with maps in a React Native application.
  • Supports a wide range of map providers, including Google Maps, Apple Maps, and Mapbox.
  • Offers advanced features like custom markers, polylines, and overlays.

Cons of react-native-maps

  • Requires additional setup and configuration for certain map providers, which can be complex for some developers.
  • May have performance issues on older or lower-end devices, especially when rendering a large number of map elements.

Code Comparison

react-native-maps:

<MapView
  style={{ flex: 1 }}
  initialRegion={{
    latitude: 37.78825,
    longitude: -122.4324,
    latitudeDelta: 0.0922,
    longitudeDelta: 0.0421,
  }}
>
  <Marker
    coordinate={{ latitude: 37.78825, longitude: -122.4324 }}
    title="Marker Title"
    description="Marker Description"
  />
</MapView>

react-native-geolocation:

Geolocation.getCurrentPosition(
  (position) => {
    console.log(position.coords.latitude);
    console.log(position.coords.longitude);
  },
  (error) => {
    console.log(error.code, error.message);
  },
  { enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 }
);

Geolocation APIs for React Native

Pros of react-native-geolocation

  • Provides a simple and straightforward API for accessing the device's geolocation in React Native applications.
  • Supports both iOS and Android platforms, making it a cross-platform solution.
  • Includes helpful utility functions for converting coordinates and calculating distances.

Cons of react-native-geolocation

  • The project appears to be less actively maintained, with the last commit being over a year ago.
  • The documentation is relatively sparse, which may make it more challenging for new users to get started.
  • There are no clear guidelines or examples for handling location permissions and error handling.

Code Comparison

Here's a brief comparison of the code for getting the current location in both repositories:

react-native-geolocation

import Geolocation from 'react-native-geolocation';

Geolocation.getCurrentPosition(
  (position) => {
    console.log(position.coords.latitude, position.coords.longitude);
  },
  (error) => {
    console.log(error.code, error.message);
  },
  { enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 }
);

react-native-geolocation

import { getCurrentPosition } from 'react-native-geolocation';

getCurrentPosition()
  .then((position) => {
    console.log(position.coords.latitude, position.coords.longitude);
  })
  .catch((error) => {
    console.log(error.code, error.message);
  });

The main difference is that the react-native-geolocation repository uses a more modern Promise-based API, while the react-native-geolocation repository uses the traditional callback-based approach.

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

Pros of react-native-background-geolocation

  • Provides more advanced features for background location tracking, such as activity recognition, geofencing, and location batching.
  • Supports both iOS and Android platforms, with a consistent API across both.
  • Offers a comprehensive set of configuration options to fine-tune the location tracking behavior.

Cons of react-native-background-geolocation

  • Larger and more complex library, which may have a higher learning curve for some developers.
  • Requires additional setup and configuration, such as configuring background permissions and location services.
  • May have a higher impact on battery life compared to a simpler geolocation library.

Code Comparison

react-native-geolocation

import { getCurrentPosition } from 'react-native-geolocation';

getCurrentPosition(
  (position) => {
    console.log(position.coords.latitude, position.coords.longitude);
  },
  (error) => {
    console.log(error.message);
  }
);

react-native-background-geolocation

import BackgroundGeolocation from '@transistorsoft/react-native-background-geolocation';

BackgroundGeolocation.start();
BackgroundGeolocation.on('location', (location) => {
  console.log(location.latitude, location.longitude);
});

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-community/geolocation

npm Supports Android, iOS and web MIT License

The Geolocation API 📍 module for React Native that extends the Geolocation web spec.

Supports TurboModules ⚡️ and legacy React Native architecture.

Fully compatible with TypeScript.

Supports modern Play Services Location API.

Supported platforms

PlatformSupport
iOS✅
Android✅
Web✅
Windows❌
macOS❌

Compatibility

React NativeRNC Geoloaction
>= 0.73.0>= 3.2.0
>= 0.70.0>= 3.0.0 < 3.2.0
>= 0.64.02.x.x
<= 0.63.01.x.x

Getting started

yarn add @react-native-community/geolocation

or

npm install @react-native-community/geolocation --save

Configuration and Permissions

iOS

You need to include NSLocationWhenInUseUsageDescription and NSLocationAlwaysAndWhenInUseUsageDescription in Info.plist to enable geolocation when using the app. If your app supports iOS 10 and earlier, the NSLocationAlwaysUsageDescription key is also required. If these keys are not present in the Info.plist, authorization requests fail immediately and silently. Geolocation is enabled by default when you create a project with react-native init.

In order to enable geolocation in the background, you need to include the 'NSLocationAlwaysUsageDescription' key in Info.plist and add location as a background mode in the 'Capabilities' tab in Xcode.

IOS >= 15 Positions will also contain a mocked boolean to indicate if position was created from a mock provider / software.

Android

To request access to location, you need to add the following line to your app's AndroidManifest.xml:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

or

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

Android API >= 18 Positions will also contain a mocked boolean to indicate if position was created from a mock provider.

Android API >= 23 Requires an additional step to check for, and request the ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION permissions using the PermissionsAndroid API. Failure to do so may result in a hard crash.

For React Native < 0.65 on Android we need to link manually
  • android/settings.gradle
include ':react-native-community-geolocation'
project(':react-native-community-geolocation').projectDir = new File(rootProject.projectDir, '../node_modules/@react-native-community/geolocation/android')
  • android/app/build.gradle
dependencies {
   ...
   implementation project(':react-native-community-geolocation')
}
  • android/app/src/main/.../MainApplication.java On imports section:
import com.reactnativecommunity.geolocation.GeolocationPackage;

In the class at getPackages method:

@Override
protected List<ReactPackage> getPackages() {
      @SuppressWarnings("UnnecessaryLocalVariable")
      List<ReactPackage> packages = new PackageList(this).getPackages();
      // Packages that cannot be autolinked yet can be added manually here, for example:
      packages.add(new GeolocationPackage()); // <== add this line
      return packages;
}

Migrating from the core react-native module

This module was created when the Geolocation was split out from the core of React Native. As a browser polyfill, this API was available through the navigator.geolocation global - you didn't need to import it. To migrate to this module you need to follow the installation instructions above and change following code:

navigator.geolocation.setRNConfiguration(config);

to:

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

Geolocation.setRNConfiguration(config);

If you need to have geolocation API aligned with the browser (cross-platform apps), or want to support backward compatibility, please consider adding following lines at the root level, for example at the top of your App.js file (only for react native):

navigator.geolocation = require('@react-native-community/geolocation');

Usage

Example

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

Geolocation.getCurrentPosition(info => console.log(info));

Check out the example project for more examples.

Methods

Summary


Details

setRNConfiguration()

Sets configuration options that will be used in all location requests.

Geolocation.setRNConfiguration(
  config: {
    skipPermissionRequests: boolean;
    authorizationLevel?: 'always' | 'whenInUse' | 'auto';
    enableBackgroundLocationUpdates?: boolean;
    locationProvider?: 'playServices' | 'android' | 'auto';
  }
) => void

Supported options:

  • skipPermissionRequests (boolean) - Defaults to false. If true, you must request permissions before using Geolocation APIs.
  • authorizationLevel (string, iOS-only) - Either "whenInUse", "always", or "auto". Changes whether the user will be asked to give "always" or "when in use" location services permission. Any other value or auto will use the default behaviour, where the permission level is based on the contents of your Info.plist.
  • enableBackgroundLocationUpdates (boolean, iOS-only) - When using skipPermissionRequests, toggle wether to automatically enableBackgroundLocationUpdates. Defaults to true.
  • locationProvider (string, Android-only) - Either "playServices", "android", or "auto". Determines wether to use Google’s Location Services API or Android’s Location API. The "auto" mode defaults to android, and falls back to Android's Location API if play services aren't available.

requestAuthorization()

Request suitable Location permission.

  Geolocation.requestAuthorization(
    success?: () => void,
    error?: (
      error: {
        code: number;
        message: string;
        PERMISSION_DENIED: number;
        POSITION_UNAVAILABLE: number;
        TIMEOUT: number;
      }
    ) => void
  )

On iOS if NSLocationAlwaysUsageDescription is set, it will request Always authorization, although if NSLocationWhenInUseUsageDescription is set, it will request InUse authorization.


getCurrentPosition()

Invokes the success callback once with the latest location info.

  Geolocation.getCurrentPosition(
    success: (
      position: {
        coords: {
          latitude: number;
          longitude: number;
          altitude: number | null;
          accuracy: number;
          altitudeAccuracy: number | null;
          heading: number | null;
          speed: number | null;
        };
        timestamp: number;
      }
    ) => void,
    error?: (
      error: {
        code: number;
        message: string;
        PERMISSION_DENIED: number;
        POSITION_UNAVAILABLE: number;
        TIMEOUT: number;
      }
    ) => void,
    options?: {
        timeout?: number;
        maximumAge?: number;
        enableHighAccuracy?: boolean;
    }
  )

Supported options:

  • timeout (ms) - Is a positive value representing the maximum length of time (in milliseconds) the device is allowed to take in order to return a position. Defaults to 10 minutes.
  • maximumAge (ms) - Is a positive value indicating the maximum age in milliseconds of a possible cached position that is acceptable to return. If set to 0, it means that the device cannot use a cached position and must attempt to retrieve the real current position. If set to Infinity the device will always return a cached position regardless of its age. Defaults to INFINITY.
  • enableHighAccuracy (bool) - Is a boolean representing if to use GPS or not. If set to true, a GPS position will be requested. If set to false, a WIFI location will be requested.

watchPosition()

Invokes the success callback whenever the location changes. Returns a watchId (number).

  Geolocation.watchPosition(
    success: (
      position: {
        coords: {
          latitude: number;
          longitude: number;
          altitude: number | null;
          accuracy: number;
          altitudeAccuracy: number | null;
          heading: number | null;
          speed: number | null;
        };
        timestamp: number;
      }
    ) => void,
    error?: (
      error: {
        code: number;
        message: string;
        PERMISSION_DENIED: number;
        POSITION_UNAVAILABLE: number;
        TIMEOUT: number;
      }
    ) => void,
    options?: {
      interval?: number;
      fastestInterval?: number;
      timeout?: number;
      maximumAge?: number;
      enableHighAccuracy?: boolean;
      distanceFilter?: number;
      useSignificantChanges?: boolean;
    }
  ) => number

Supported options:

  • interval (ms) -- (Android only) The rate in milliseconds at which your app prefers to receive location updates. Note that the location updates may be somewhat faster or slower than this rate to optimize for battery usage, or there may be no updates at all (if the device has no connectivity, for example).
  • fastestInterval (ms) -- (Android only) The fastest rate in milliseconds at which your app can handle location updates. Unless your app benefits from receiving updates more quickly than the rate specified in interval, you don't need to set it.
  • timeout (ms) - Is a positive value representing the maximum length of time (in milliseconds) the device is allowed to take in order to return a position. Defaults to 10 minutes.
  • maximumAge (ms) - Is a positive value indicating the maximum age in milliseconds of a possible cached position that is acceptable to return. If set to 0, it means that the device cannot use a cached position and must attempt to retrieve the real current position. If set to Infinity the device will always return a cached position regardless of its age. Defaults to INFINITY.
  • enableHighAccuracy (bool) - Is a boolean representing if to use GPS or not. If set to true, a GPS position will be requested. If set to false, a WIFI location will be requested.
  • distanceFilter (m) - The minimum distance from the previous location to exceed before returning a new location. Set to 0 to not filter locations. Defaults to 100m.
  • useSignificantChanges (bool) - Uses 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. Defaults to FALSE.

clearWatch()

Clears watch observer by id returned by watchPosition()

Geolocation.clearWatch(watchID: number);

Maintainers

This module is developed and maintained by michalchudziak.

I owe a lot to the fantastic React & React Native community, and I contribute back with my free time 👨🏼‍💼💻 so if you like the project, please star it ⭐️!

If you need any help with this module, or anything else, feel free to reach out to me! I provide boutique consultancy services for React & React Native. Just visit my website, or send me an email at hello@michalchudziak.dev 🙏🏻

Co-maintainers needed

Due to personal commitments, recently I am unable to dedicate the necessary time to maintain this library as it deserves. I’m looking for passionate contributors to help keep the project alive and thriving. If you're interested in contributing or taking on a maintainer role, please reach out hello@michalchudziak.dev — your support would mean a lot!

Contributors

This module was extracted from react-native core. Please refer to https://github.com/react-native-community/react-native-geolocation/graphs/contributors for the complete list of contributors.

License

The library is released under the MIT licence. For more information see LICENSE.

NPM DownloadsLast 30 Days