Cyber Monday Sale

1/ 100

promotion ends on December 7th

Mega Bundle 🔥🔥🔥

Get developer licenses for all our products at 95% off discount.

$9,981

$699

  • 20+ fully functional mobile apps
  • 700+ screens
  • 2,000+ features
  • 250,000+ lines of code
  • fully customizable codebase
  • 1000+ paid customers
  • 60,000+ developers using our products
  • free 1 year updates
BUY NOW

It’s nearly impossible to build a mobile app these days without needing to access your users’ location in order to improve the user experience tremendously. In this article, we will be looking at how to get user location in React Native, without having your app crash.

We will be exploring two React Native libraries that will help us fetch the user location:

  • expo-location
  • @react-native-community/geolocation

react native location

Get User Location in React Native with expo-location Package

This library is offered by Expo and is my personal preference because you don’t have to import a separate dependency to access the permission library. The only issue with expo-location is that it requires a one-time additional setup of react-native-unimodules after installation.

Installation

I you are working on an expo project:

expo install expo-location

but for bare projects, depending on your preferred package manager:

yarn add expo-location

or

npm install expo-location

Add NSLocationAlwaysAndWhenInUseUsageDescription, NSLocationAlwaysUsageDescription and NSLocationWhenInUseUsageDescription keys to your Info.plist:

<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>Allow $(PRODUCT_NAME) to use your location</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>Allow $(PRODUCT_NAME) to use your location</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>Allow $(PRODUCT_NAME) to use your location</string>

and confirm that you have added the following permissions to the AndroidManifest.xml

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

Firstly, you want to ask the user for permission. If you don’t do this, your React Native app might crash when accessing the location:

import * as Location from 'expo-location';

const checkPermission = async () => {
  const hasPermission = await Location.requestPermissionsAsync();
  if (!hasPermission.status === 'granted') {
    console.log('the user has not granted you permission')
  }
};

Next up is to ask for the location permission:

import * as Location from 'expo-location';

const checkPermission = async () => {
  const hasPermission = await Location.requestPermissionsAsync();
  if (hasPermission.status === 'granted') {
    const permission = await askPermission();
    return permission;
  }

  return true;
};

const askPermission = async () => {
  const permission = await Location.getPermissionsAsync();
  return permission.status === 'granted';
};

Basically, the above codebase checks if permission has been granted and asks for permission if permission has not already been granted or rejected.

After the user has granted your app the location permission, accessing the location of the user is simply a function call away:

export const getUserLocation = async () => {
  const userLocation = await Location.getCurrentPositionAsync();
  return userLocation.coords;
};

the format for the coordinate is

{
  "accuracy", 
  "altitude", 
  "altitudeAccuracy", 
  "heading", 
  "latitude", 
  "longitude",
  "speed":
}

Get User Location in React Native with @react-native-community/geolocation

This is the more official React Native dependency for fetching the user location. This one does not work with Expo projects though.

Installation
 yarn add @react-native-community/geolocation

For iOS:

You need to includeNSLocationWhenInUseUsageDescriptionandNSLocationAlwaysAndWhenInUseUsageDescriptioninInfo.plistto enable geolocation when using the app. If your app supports iOS 10 and earlier, theNSLocationAlwaysUsageDescriptionkey is also required. If these keys are not present in theInfo.plist, authorization requests fail immediately and silently. Geolocation is enabled by default when you create a project withreact-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.

For Android:

To request access to location, you need to add the following line to your app’sAndroidManifest.xml:

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

Android API >= 18 Positions will also contain amockedboolean 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 permission using thePermissionsAndroid API. Failure to do so may result in a hard crash.

Usage

For this particular dependency you should ask for permissions first using PermissionAndroid, an inbuilt React Native module that does not need any installation, before fetching users’ permission.

Geolocation.getCurrentPosition(
  (position) => {
    setUserLocation(position);
  },
  (error) => Alert.alert('Error', JSON.stringify(error)),
    {enableHighAccuracy: true, timeout: 20000, maximumAge: 1000},
  );

Both libraries offer the same data structure for their coordinates.

Conclusion on How to Get User Location in React Native

We have succeeded in exploring the two alternative dependencies that can be used to fetch user location in React Native. One thing to note is that you have to always ask for the location permission first to ensure your mobile application won’t crash in production.

Categories: React Native

Leave a Reply

Your email address will not be published. Required fields are marked *

Shopping Cart