Emmanuel Oaikhenan I started coding JavaScript in 2017 and delved into DevOps in 2019. Since then, I've worked on projects that exposed me to learning more about software development and gained the requisite soft skills for communicating with teammates and clients.

React Native geolocation: A complete tutorial

9 min read 2717

React Native Geolocation

Editor’s note: This article was last updated 21 September 2022 to reflect changes made to the React Native CLI. 

You may have wondered how food delivery and ride-hailing apps know where you are at a given point in time. The answer is geolocation.

In this tutorial, we’ll learn how to implement geolocation in React Native. We’ll build an example app that displays the user’s location on a map with longitude and latitude coordinates and enables the user to send their location to another source, like Twitter.

We’ll cover the following:

You can access the full source code for this project on GitHub. Let’s get started!

What is geolocation?

Geolocation is the ability to detect the geographic position of a device that is connected to the internet. One simple example of geolocation is using a device’s IP address to determine the country, city, or postal code at which it is located. Most of the time, the user must grant permission for an app to access their location data.

Geolocation in React Native

React Native provides the @react-native-community/geolocation API for geolocation. However, Google does not recommend using the React Native API for geolocation because it is less accurate and slower than the recommended Google Location Services API.

Thankfully, the React Native community has developed several excellent libraries for implementing geolocation in React Native, including react-native-location and react-native-geolocation-service.

In this React Native geolocation tutorial, we’ll use the react-native-geolocation-service library, which is available as a Node package on npm.

We’ll build an app that does the following:

  • Asks permission to access location data on your Android and iOS device
  • Picks your location coordinates
  • Saves or sends your location coordinates

It is recommended to use Node.js ≥v10. To check your Node.js version, run the code below:

$ node -v

// returns node version

You can use nvm to manage multiple Node.js versions installed on your machine. React Native has a built-in command line interface that you can use to generate a new project. You can access it without installing anything globally using npx, which ships with Node.js.

Initialize a React Native project

To get started, run the following command in your terminal:

$ npx react-native init ReactNativeGeolocation

npx is a Node-based command that you can use to run Node-based dependencies in your terminal without having to install them on your machine.

The init part of the command is the instruction to initialize a new React Native project with ReactNativeLocation as the directory where the project files will be installed.

The npx react-native command works without having to install React Native on your machine. Alternatively, you can install React Native globally on your machine to run React Native commands without using npx. To install React Native globally, run the following command:

$ npm install -g react-native-cli

You can then check that React Native is installed using the command below:

$ react-native -v

The command above prints the React Native version installed on your machine to the console. Open up your favorite IDE and go to the ReactNativeGeolocation directory. The command we ran to initialize the project has set up the React Native app for us.

We’ll write all of our code in the App.js file. Make sure you’re in the root directory of your app to run the commands.

The first step is to start Metro. Metro is a JavaScript bundler that ships with React Native. Metro takes in an entry file and various options, then returns a single JavaScript file that includes all your code and its dependencies:

$ npx react-native start

With Metro running in your terminal, open another terminal and run the following command:

$ npx react-native run-android

To run the app, you’ll need either an Android emulator or a mobile device connected to your PC in debug mode. However, if you’re using Android Studio’s emulator, you may run into an error for the following reasons:

  • You need to define an ANDROID_HOME env variable that points to the SDK directory
  • You need to accept all the SDK licenses

You should then see the following screen:

React Native New App Screen

We can start making changes to the app in our App.js folder. Remove all the old code in App.js and replace it with the following:

/**
* Sample React Native App
* https://github.com/facebook/react-native
*
* @format
* @flow strict-local
*/

import React from 'react';
import {StyleSheet, View, Text} from 'react-native';

const App = () => {
 return (
   <View style={styles.container}>
     <Text>Welcome!</Text>
   </View>
 );
};

const styles = StyleSheet.create({
 container: {
   flex: 1,
   backgroundColor: '#fff',
   alignItems: 'center',
   justifyContent: 'center',
 },
});

export default App;

The code above gives us a new screen where we can continue writing our program:

React Native New App Welcome Screen

Required dependencies for geolocation in React Native

Install the react-native-geolocation-service library using either Yarn or npm with the respective codes below:

$ yarn add react-native-geolocation-service
$ npm install react-native-geolocation-service --save

In the past, you’d have to link the library, but in more recent versions of React Native, this is done automatically when running a build with npx react-native run-android or the iOS equivalent.

Previously, you’d use an npx react-native link command, which is no longer part of the React Native CLI. If you are using React Native ≤v0.60, then these linking directions should help you get set up.

We also want to make sure that we enable permissions in the app by adding the following code to android/src/main/AndroidManifest.xml:

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

Then, run npx react-native run-android again.

Adding geolocation to a React Native app

Let’s add two separate buttons to our React Native app, one to get the user’s location, which we’ll store in the app state, and another to send the user’s location to Twitter.



We’ll add two buttons to App.js under the welcome text. Make sure to update the imports from React Native to include Button as import {StyleSheet, View, Text, Button} from 'react-native';:

  return (
    <View style={styles.container}>
      <Text>Welcome!</Text>
      <View
        style={{marginTop: 10, padding: 10, borderRadius: 10, width: '40%'}}>
        <Button title="Get Location" />
      </View>
      <Text>Latitude: </Text>
      <Text>Longitude: </Text>
      <View
        style={{marginTop: 10, padding: 10, borderRadius: 10, width: '40%'}}>
        <Button title="Send Location" />
      </View>
    </View>
  );
};

Now, our app looks like the image below:

React Native Latitude Longitude Geolocation

Importing react-native-library

Once we have the react-native-geolocation-service library installed, we can implement the logic to get the latitude and longitude coordinates. Using ES6, we’ll write an async request that the onPress button event will handle, which is triggered by the GET LOCATION button.

Once this event handler is triggered, the user is asked for permission to access their location. Upon granting the request, the location will be returned to the user.

First, we need to import react-native-geolocation-service as follows:

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

Requesting permission to access location data

To use the phone’s geolocation feature, we’ll have to ask the user for the proper permissions. In the code below, we have a function to request permission on an Android device.

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

// Function to get permission for location
const requestLocationPermission = async () => {
  try {
    const granted = await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
      {
        title: 'Geolocation Permission',
        message: 'Can we access your location?',
        buttonNeutral: 'Ask Me Later',
        buttonNegative: 'Cancel',
        buttonPositive: 'OK',
      },
    );
    console.log('granted', granted);
    if (granted === 'granted') {
      console.log('You can use Geolocation');
      return true;
    } else {
      console.log('You cannot use Geolocation');
      return false;
    }
  } catch (err) {
    return false;
  }
};

For iOS app permissions, you can read this article on iOS permission flow or try this unified iOS/Android permissions library.

In the function above, we make a call to the request function to request permission from the issuer. We specify that we are requesting the ACCESS_FINE_LOCATION permission, which must’ve been added to the Android Manifest earlier and rebuilt.

Then, we pass an object with the details of prompt. The result of the request is stored in the variable granted, which will store the string granted if successful. If the request was successful, we return true, if not, we return false.

Getting the user’s location data

Now, from inside our component, we’ll create state to track our users’ location. First, be sure that you imported useState from React:

  // state to hold location
  const [location, setLocation] = useState(false);

We’ll then write a function so that when the GET LOCATION button is pressed, it’ll request permission. If permission is granted, it will get the user’s current location:

  // function to check permissions and get Location
  const getLocation = () => {
    const result = requestLocationPermission();
    result.then(res => {
      console.log('res is:', res);
      if (res) {
        Geolocation.getCurrentPosition(
          position => {
            console.log(position);
            setLocation(position);
          },
          error => {
            // See error code charts below.
            console.log(error.code, error.message);
            setLocation(false);
          },
          {enableHighAccuracy: true, timeout: 15000, maximumAge: 10000},
        );
      }
    });
    console.log(location);
  };

We see ourselves call the requestLocationPermission function that we wrote earlier, which will return a promise that will resolve to either true or false. If the promise resolves to true, we use the react-native-geolocation-service library to get the correct position and set the location state to the result. If the promise is false, meaning permission wasn’t given, or if it fails to get the location, it will set the location state to false.

We then add the getLocation function as an onPress event on the GET LOCATION button:

<Button title="Get Location" onPress={getLocation} />

So far, your App.js should look like the code below:

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow strict-local
 */
import React, {useState, useEffect} from 'react';
import {StyleSheet, View, Text, Button, PermissionsAndroid} from 'react-native';
import Geolocation from 'react-native-geolocation-service';
// Function to get permission for location
const requestLocationPermission = async () => {
  try {
    const granted = await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
      {
        title: 'Geolocation Permission',
        message: 'Can we access your location?',
        buttonNeutral: 'Ask Me Later',
        buttonNegative: 'Cancel',
        buttonPositive: 'OK',
      },
    );
    console.log('granted', granted);
    if (granted === 'granted') {
      console.log('You can use Geolocation');
      return true;
    } else {
      console.log('You cannot use Geolocation');
      return false;
    }
  } catch (err) {
    return false;
  }
};
const App = () => {
  // state to hold location
  const [location, setLocation] = useState(false);
  // function to check permissions and get Location
  const getLocation = () => {
    const result = requestLocationPermission();
    result.then(res => {
      console.log('res is:', res);
      if (res) {
        Geolocation.getCurrentPosition(
          position => {
            console.log(position);
            setLocation(position);
          },
          error => {
            // See error code charts below.
            console.log(error.code, error.message);
            setLocation(false);
          },
          {enableHighAccuracy: true, timeout: 15000, maximumAge: 10000},
        );
      }
    });
    console.log(location);
  };
  return (
    <View style={styles.container}>
      <Text>Welcome!</Text>
      <View
        style={{marginTop: 10, padding: 10, borderRadius: 10, width: '40%'}}>
        <Button title="Get Location" onPress={getLocation} />
      </View>
      <Text>Latitude: {location ? location.coords.latitude : null}</Text>
      <Text>Longitude: {location ? location.coords.longitude : null}</Text>
      <View
        style={{marginTop: 10, padding: 10, borderRadius: 10, width: '40%'}}>
        <Button title="Send Location" />
      </View>
    </View>
  );
};
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});
export default App;

When it runs, and you click the GET LOCATION button, you’ll see a pop-up like the following:

React Native Geolocation Get Location Popup

React Native Access Location Data Prompt

Then, your location should show up on the screen as shown below:

Geolocation Latitude Longitude Data Screen

The Location object

The location object you’ll get back from react-native-geolocation-service will look something like the code below:

{
  "coords": {
    "accuracy": 5,
    "altitude": 5,
    "altitudeAccuracy": 0.5,
    "heading": 0,
    "latitude": 37.4219983,
    "longitude": -122.084,
    "speed": 0
  },
  "mocked": false,
  "provider": "fused",
  "timestamp": 1662837540458
}

Sending geolocation data in React Native

To send the user’s geolocation data to Twitter, we simply need to turn the SEND LOCATION button into a Tweet button.

Before we send the location to the user, we’ll display the data returned in the example. To do so, we add the useState Hook from React to our app as follows:

import React, { useState } from 'react';

Then, we define a state inside our App function:

[viewLocation, isViewLocation] = useState([])

We update the if statement to call the isViewLocation method and update the viewLocation array with the Location information object returned:

isViewLocation(location)

To view the information returned, update the Location and Longitude text tags:

<Text>Latitude: {viewLocation.latitude} </Text>
<Text>Longitude: {viewLocation.longitude} </Text>

viewLocation.latitude returns the latitude in the object response called by the method isViewLocation. The same goes for the longitude.

At this point, we can update the button to send the user’s location to Twitter. The image below shows a view of our final example app:

Send Geolocation Data Twitter React Native

Sending user location data to Twitter

Next, we’ll set up the SEND LOCATION button to add the user’s location to a new Tweet:

  // Function to Send Location to twitter
  const sendLocation = () => {
    try {
      if (location) {
        const tweet = `latitude is ${location.coords.latitude} and longitude is ${location.coords.longitude}`;
        const url = `https://twitter.com/intent/tweet?text=${tweet}`;
        Linking.openURL(url);
      }
    } catch (error) {
      console.log(error);
    }
  };

The function above:

  • Checks if we have a location in our state. If we don’t, location will equal false
  • Constructs a string to be our Tweet with our latitude and longitude
  • Constructs a URL to create the Tweet
  • Uses the Linking object to open the URL. Make sure to import Linking from React Native

Now, when you click on the SEND LOCATION button, you should end up with a browser window that looks like the following image:

Send Location Button Browser Window

The final App.js file should look like the following code:

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow strict-local
 */
import React, {useState, useEffect} from 'react';
import {
  StyleSheet,
  View,
  Text,
  Button,
  PermissionsAndroid,
  Linking,
} from 'react-native';
import Geolocation from 'react-native-geolocation-service';
// Function to get permission for location
const requestLocationPermission = async () => {
  try {
    const granted = await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
      {
        title: 'Geolocation Permission',
        message: 'Can we access your location?',
        buttonNeutral: 'Ask Me Later',
        buttonNegative: 'Cancel',
        buttonPositive: 'OK',
      },
    );
    console.log('granted', granted);
    if (granted === 'granted') {
      console.log('You can use Geolocation');
      return true;
    } else {
      console.log('You cannot use Geolocation');
      return false;
    }
  } catch (err) {
    return false;
  }
};
const App = () => {
  // state to hold location
  const [location, setLocation] = useState(false);
  // function to check permissions and get Location
  const getLocation = () => {
    const result = requestLocationPermission();
    result.then(res => {
      console.log('res is:', res);
      if (res) {
        Geolocation.getCurrentPosition(
          position => {
            console.log(position);
            setLocation(position);
          },
          error => {
            // See error code charts below.
            console.log(error.code, error.message);
            setLocation(false);
          },
          {enableHighAccuracy: true, timeout: 15000, maximumAge: 10000},
        );
      }
    });
    console.log(location);
  };
  // Function to Send Location to twitter
  const sendLocation = () => {
    try {
      if (location) {
        const tweet = `latitude is ${location.coords.latitude} and longitude is ${location.coords.longitude}`;
        const url = `https://twitter.com/intent/tweet?text=${tweet}`;
        Linking.openURL(url);
      }
    } catch (error) {
      console.log(error);
    }
  };
  return (
    <View style={styles.container}>
      <Text>Welcome!</Text>
      <View
        style={{marginTop: 10, padding: 10, borderRadius: 10, width: '40%'}}>
        <Button title="Get Location" onPress={getLocation} />
      </View>
      <Text>Latitude: {location ? location.coords.latitude : null}</Text>
      <Text>Longitude: {location ? location.coords.longitude : null}</Text>
      <View
        style={{marginTop: 10, padding: 10, borderRadius: 10, width: '40%'}}>
        <Button title="Send Location" onPress={sendLocation} />
      </View>
    </View>
  );
};
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});
export default App;

Conclusion

Now that you know how to acquire a user’s location, there’s a lot more you can do. You can build a delivery service, track a user, and even build an emergency button alert system. The possibilities are endless. In this tutorial, we just scratched the surface, exploring the react-native-geolocation-service library to build our example application.

Geolocation is a really interesting feature with a wide variety of real-world use cases. Let me know in the comments how you plan to use geolocation in your React Native app. Happy coding!

LogRocket: Instantly recreate issues in your React Native apps.

LogRocket is a React Native monitoring solution that helps you reproduce issues instantly, prioritize bugs, and understand performance in your React Native apps.

LogRocket also helps you increase conversion rates and product usage by showing you exactly how users are interacting with your app. LogRocket's product analytics features surface the reasons why users don't complete a particular flow or don't adopt a new feature.

Start proactively monitoring your React Native apps — .

Emmanuel Oaikhenan I started coding JavaScript in 2017 and delved into DevOps in 2019. Since then, I've worked on projects that exposed me to learning more about software development and gained the requisite soft skills for communicating with teammates and clients.

20 Replies to “React Native geolocation: A complete tutorial”

  1. Hello Emmanuel, just to help the other people going through this article. I noticed a small ‘possible modification’.
    When you mention the “getLocation” function in the finishing paragraph I found myself in a state of minute confusion. After checking the source code it makes sense that you have replaced that function with “permissionHandle”

  2. Thank you for reading the article Mushtaq! I do hope you found it useful. Thank you much more for pointing that out.

    1. You are welcome brother! Thank you for the kind words! Please, do kindly share across your social media platforms so that others can find the article. Thank you for reading!

    1. You are welcome brother! Thank you for the kind words! Please, do kindly share across your social media platforms so that others can find the article. Thank you for reading!

  3. This might be due for an update given react-native-location hasn’t been updated in over 3 years.

  4. Hi. The timestamp is of the cellular network or from the telephone’s clock? Thanks

    1. The timestamp is based on the user location and returned from the `react-native-geolocation` library. It is calculated using the Date Time object. It is returned using `location.getTime()`. It is therefore not based on the telephone clock or cellular network.

  5. TypeError: null is not an object (evaluating ‘RNFusedLocation.getCurrentPosition’)
    Get This Error

  6. after init I only had 3 files, I couldn’t run the project. As a beginner I don’t know what to do now

Leave a Reply