React Native Geolocation Service

Learn via video courses
Topics Covered

Overview

You may have questioned how ride-hailing and meal delivery services can pinpoint your whereabouts at any given time. React native geolocation service is the solution. We will learn how to build geolocation in React Native in this tutorial. We'll create an example app that allows users to communicate their position to Twitter or another source, such as a map showing their location with longitude and latitude information.

Understanding Geolocation

The ability to determine a connected device's geographic location is known as geolocation. Using a device's IP address to establish its location by city, state, or postal code is one straightforward example of geolocation. The user often has to give consent for an application to obtain their location data.

Geolocation and Use of React Native

The @react-native-community/geolocation API from React Native is available for geolocation. Google does not advise utilizing the React Native API for geolocation, though, as it is slower and less precise than the Google Location Services API, which is advised. Thankfully, the React Native community has created several top-notch libraries, like react-native-location and react-native-geolocation-service, for integrating React native geolocation service. The react-native-geolocation-service library, which is offered as a Node package on npm, will be used in this React Native geolocation article.

We'll create an application that can :

  • Requests authorization to access location information on your iOS and Android smartphone.
  • Choose your location coordinates.
  • Your location coordinates are to be saved or sent.

It is advised to utilize Node.js version 10. Run the following code to determine your Node.js version :

Multiple Node.js versions that are installed on your computer may be managed with nvm. You may create a new project using the built-in command line interface of React Native. Using npx, a component of Node.js, you may access it without installing anything on a global scale.

What is react-native-geolocation-service?

With the current implementation of the React native geolocation service API in react-native, this library was developed to address the location timeout problem on Android. The new FusedLocationProviderClient API from Google Play Service, which Google highly advises over Android's default framework location API, is utilized by this module to try to address the problem.

How to Install

Command to install the react-native-geolocation-service

yarn

*npm

Setup and Compatibility

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

Use Cases

  • Location-Based Services : With React native geolocation service, you can develop location-based services such as weather apps, restaurant finders, tourist guides, and real-time navigation applications. By utilizing the device's geolocation capabilities, you can provide users with personalized information and services based on their current location.
  • Geofencing : Geofencing involves defining virtual boundaries around specific geographic areas and triggering actions when a user enters or exits those areas. React Native Geolocation Service enables you to implement geofencing functionality in your app. This can be useful for applications such as location-based reminders, proximity-based notifications, and access control systems.
  • Tracking Applications : If you need to track the movement of users or objects, React Native Geolocation Service can be a valuable tool. You can develop applications that track delivery drivers, monitor the movement of vehicles or assets, or enable social check-ins. By continuously obtaining location updates, you can keep track of the real-time location information of the tracked entities.
  • Fitness and Health Apps : React Native Geolocation Service can be utilized to develop fitness and health applications that track users' activities, calculate distances, and provide location-based workout recommendations. Whether it's running, cycling, hiking, or other outdoor activities, you can leverage geolocation data to enhance fitness tracking experiences.
  • On-Demand Services : React Native Geolocation Service can power on-demand service applications such as ride-hailing, food delivery, and home services. By retrieving the user's current location, you can connect them with nearby service providers, calculate accurate distances and ETAs, and facilitate seamless service booking and delivery.

React-native-geolocation-service APIs

React native geolocation service has the following APIs :

  • async requestAuthorization(authorizationLevel) (iOS only) based on the authorizationLevel parameter, request location permission. either "whenInUse" or "always" are options. During setup, the list keys must be configured. Returns the permission status when the promise is resolved.

    • disabled - Location service is disabled
    • granted - Permission granted
    • denied - Permission denied
    • restricted - Permission restricted
  • getCurrentPosition(successCallback, ?errorCallback, ?options) successCallback : provides the most recent location information. errorCallback : invoked each time an error occurs. Options :

    • Name: Request timeout
    • maximumAge : How long the previous location will be cached?
    • accuracy: If not provided or provided with an invalid value, falls back to use enableHighAccuracy.
    • enableHighAccuracy : Use high accuracy mode.
    • distanceFilter: Minimum displacement in meters.
    • showLocationDialog: Whether to ask in Android to enable location. (only for Android).
    • forceRequestLocation: Improve accuracy dialogue by making the location request even after being denied. (Android only).
    • forceLocationManager : If true, Android's default LocationManager API will be used. (android only).
  • watchPosition(successCallback, ?errorCallback, ?options) successCallback : provides the most recent location information. errorCallback : invoked each time an error occurs. Options :

    • accuracy : When a value is missing or incorrect, fallback to using enableHighAccuracy.
    • enableHighAccuracy : Use high accuracy mode
    • distanceFilter : Minimum distance in meters between location updates.
    • interval : Update frequency for active locations. (android only)
    • fastestInterval : The fastest pace at which your application will get location updates, which in some circumstances (such as if other apps are initiating location updates) may be quicker than interval (android only)
    • showLocationDialog : whether to request that Android enable location. (android only)
    • forceRequestLocation : Improve accuracy dialogue by making the location request even after being denied. (android only)
    • forceLocationManager : If true, Android's default LocationManager API will be used. (android only)
    • useSignificantChanges : Returns locations using the battery-friendly native major changes APIs. Only when the device recognises that a substantial distance has been crossed will locations be returned (iOS only).
    • showsBackgroundLocationIndicator: This option makes the iOS status bar display a blue bar or blue pill. The system uses this attribute to decide whether to modify the status bar's look to show that location services are active when the app goes to the background. For users to return to your app, simply press the indication. (Apple only)
    • clearWatch(watchId) : watchId (id returned by watchPosition)
    • stopObserving() : Stops keeping track of changes in device location. All previously registered listeners are also deleted.

Error Codes

React native geolocation service has the following error codes :

  • PERMISSION_DENIED : Location authorization is not given.
  • POSITION_UNAVAILABLE : Provider of location is unavailable.
  • TIMEOUT : Request for location timed out.
  • PLAY_SERVICE_NOT_AVAILABLE : There is no Google Play service installed or it has an outdated version. (android only)
  • SETTINGS_NOT_SATISFIED : Location service is not enabled or the current request does not support the current location mode. (Android only)
  • INTERNAL_ERROR : For whatever reason, the library crashed, or getCurrentActivity() returned null. (android only)

How to Add Geolocation to a React Native App?

Permission Request for Accessing Location Data

We'll need the user's consent in order to access the phone's geolocation capability. We have a method to ask for permission on an Android smartphone in the code below.

Make sure to import PermissionsAndroid as follows import {StyleSheet, View, Text, Button, PermissionsAndroid} from 'react-native';

You may read this article on the iOS permission flow or use this combined iOS/Android permissions library for iOS app permissions.

To ask the issuer for authorization, we use the request function in the aforementioned function. The ACCESS_FINE_LOCATION permission must have been earlier added to the Android Manifest and regenerated, as we specifically state that we are asking for it.

Then, we pass an item containing the prompt's information. The granted variable, which if successful stores the string granted, holds the result of the request. We return true if the request was successful and false otherwise.

How to Get the User’s Location

Now we'll build a state from within our component so that we can monitor the position of our users. Make sure you imported useState from React first :

Then, we'll create a function that will ask for authorization when the GET LOCATION button is pressed. Upon approval, it will obtain the user's current location :

We notice that we are using the earlier-created requestLocationPermission method, which will yield a promise that may be resolved as either true or false. We make use of the react-native-geolocation-service library to obtain the precise location and set the location state to the outcome if the promise resolves to true. It will set the location state to false if the promise is false, indicating that permission was not granted, or if it is unable to obtain the location.

When the GET LOCATION button is pressed, the getLocation function is added as an onPress event :

Now your App.js file will look like this :

When it's running and you click the GET LOCATION button, a pop-up window will appear as follows :

Get location button

Your location should then be displayed on the screen as in the example below :

Get location button1

The Location object:

React-native-geolocation-service will provide a location object that resembles the code below :

Using react-native-geolocation-service for Sending Geolocation Data

We only need to change the communicate LOCATION button into a Tweet button to communicate the user's geolocation information to Twitter.

We'll first show the information received in the example before sending the user's location. To do this, we add the React useState Hook as follows to our application :

Then, inside our App function, we define a state :

The view location array is updated using the received Location information object, and the if statement is updated to invoke the isViewLocation method :

Update the Location and Longitude text tags to see the data returned :

The function isViewLocation's callback, viewLocation.latitude, returns the latitude from the object response. The longitude is the same.

We may now update the button to notify Twitter of the user's location. The view of our last example app is depicted in the picture below :

last example app

Sharing User Location to Twitter

The SEND LOCATION button will then be configured to add the user's location to a new Tweet :

The function above :

  • Determines whether we have a location in our state. Location will equal false if we don't.
  • Creates a string with our latitude and longitude to be our tweet.
  • Creates a URL to be used in the Tweet.
  • Opens the URL using the Linking object. Ensure that Linking is imported from React Native.

Now, when you press the SEND LOCATION button, the browser window that appears should resemble the one below :

Location button

The following code should appear in the final App.js file :

FAQs

Q. Can I track the user's location continuously in the background using this library?

A. Yes, react-native-geolocation-service supports background geolocation, allowing you to track the user's location even when your app is running in the background. This is useful for location-based services and tracking applications.

Q. How can I handle errors that occur during geolocation operations?

A. The library provides error-handling mechanisms to help you handle various geolocation-related errors. You can use try-catch blocks or error callbacks to handle errors and provide appropriate feedback to the user.

Q. Is react-native-geolocation-service actively maintained?

A. Yes, react-native-geolocation-service is actively maintained by its developers and has a supportive community. This ensures regular updates, bug fixes, and access to community-driven resources for troubleshooting and enhancements.

Q. Can I customize the React native geolocation service settings and parameters?

A. Yes, react-native-geolocation service allows you to customize geolocation settings and parameters based on your requirements. You can specify accuracy levels, update intervals, and other configuration options to fine-tune the geolocation behavior.

Q. Does react-native-geolocation-service provide accurate location data?

A. Yes, the library utilizes the React native geolocation service of the device to provide accurate location data. It leverages the capabilities of the underlying operating system to deliver precise location information.

Conclusion

  • The ability to determine a connected device's geographic location is known as geolocation.
  • react-native-geolocation-service library offers a straightforward integration process, allowing developers to quickly add geolocation capabilities to their React Native apps.
  • React Native Geolocation Service supports both iOS and Android platforms, enabling developers to build geolocation features that work seamlessly across different devices.
  • The library implements efficient algorithms to optimize battery usage during location tracking, minimizing the impact on device battery life.
  • The library supports background geolocation, allowing continuous location tracking even when the app is running in the background.
  • React Native Geolocation Service provides robust error handling mechanisms, allowing developers to handle various location-related errors gracefully and provide appropriate feedback to users.
  • The @react-native-community/geolocation API from React Native is available for geolocation.
  • The error codes are PERMISSION_DENIED, POSITION_UNAVAILABLE, TIMEOUT etc.
  • React-native-geolocation-service APIs are async requestAuthorization(authorizationLevel) (iOS only), getCurrentPosition(successCallback, ?errorCallback, ?options), watchPosition(successCallback, ?errorCallback, ?options) etc.
  • The library is actively maintained and has a supportive community of developers.
  • React Native Geolocation Service offers comprehensive documentation and examples, making it easier for developers to understand and utilize the library effectively.