Using Geolocation in React Native


React Native takes advantage of Geolocation API that is by default accessible in the web. This API returns different methods such as getCurrentPosition, and watchPosition which are available in React Native as polyfill. To demonstrate how to use it in a React Native app we will integrate it using react-native-cli.

Getting Started

Using react-native-cli means there are no templates and only little boilerplate code to get started. We will generate a project using the following command. If you do not have it installed in your local machine, please use the first command mentioned below.

1# to install the cli
2npm install -g react-native-cli
4# to scafold an RN project
5react-native init geo-example

So once the project directory is generated, traverse into it and run npm start to see if everything is installed correctly. If you are on Mac, you can use the ios simulator to verify. For Windows plus other linux distro users, android emulator is your friend.

Accessing Geolocation API

The Geolocation API exists as a global object called navigator object in React Native, just like the web. It is accessible via navigator.geolocation in our source code and there is no need to import it.

For our demonstration purposes, we will be using getCurrentPosition method from the geolocation API. This method allows a mobile app to request a user's location and accepts three parameters: success callback, error callback and a configuration object in the last.

2 position => {
3 const location = JSON.stringify(position)
5 this.setState({ location })
6 },
7 error => Alert.alert(error.message),
8 { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 }

The callback above has a position argument that is an object with the following properties if executeed without any errors.

2 "timestamp": 1533729980953.91
3 "coords": {
4 "accuracy": 5,
5 "altitude": 0,
6 "altitudeAccuracy": -1,
7 "heading": -1,
8 "latitude": 37.785834,
9 "longitude": -122.406417,
10 "speed": -1
11 }

We will modify App.js in our react-native project to get started. We start by defining a basic class component that displays the text Find My Coords?.

1import React, { Component } from 'react'
2import { View, Text } from 'react-native'
4export default class App extends Component {
5 render() {
6 return (
7 <View>
8 <Text>Find My Coords?</Text>
9 </View>
10 )
11 }

Implmenting Geolocation API

Now, let us implement the Geolocation API function getCurretPosition in our app. Open App.js and write the following code.

1import React, { Component } from 'react'
2import {
3 Platform,
4 StyleSheet,
5 Text,
6 View,
7 Alert,
8 TouchableOpacity
9} from 'react-native'
11export default class App extends Component {
12 state = {
13 location: null
14 }
16 findCoordinates = () => {
17 navigator.geolocation.getCurrentPosition(
18 position => {
19 const location = JSON.stringify(position)
21 this.setState({ location })
22 },
23 error => Alert.alert(error.message),
24 { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 }
25 )
26 }
28 render() {
29 return (
30 <View style={styles.container}>
31 <TouchableOpacity onPress={this.findCoordinates}>
32 <Text style={styles.welcome}>Find My Coords?</Text>
33 <Text>Location: {this.state.location}</Text>
34 </TouchableOpacity>
35 </View>
36 )
37 }

We start be importing TouchableOpcaity. It is a wrapper that responds accurately to user touches. In a react-native mobile app, you will be making use of them quite often. Think of it as a button in a web application. This newly imported wrapper accepts an onPress prop that is going to trigger the function defined as in the value, in our case findCoordinates.

findCoordinates holds the logic of fetching a user's location. We are also using the local state to display coordinates from the data provided to us by position object. The text Find My Coords?now becomes clickable.

You define the following styles too.

1const styles = StyleSheet.create({
2 container: {
3 flex: 1,
4 justifyContent: 'center',
5 alignItems: 'center',
6 backgroundColor: '#F5FCFF'
7 },
8 welcome: {
9 fontSize: 20,
10 textAlign: 'center',
11 margin: 10
12 },
13 instructions: {
14 textAlign: 'center',
15 color: '#333333',
16 marginBottom: 5
17 }

However, this will not work as expected. We need to set permissions to access a user's location. Also, in real time you will have to ask for permissions. Getting hands dirty now on this will benefit you. This is our next step.

Asking for Permissions

In iOS, geolocation is enabled by default when a project is created using react-native-cli. To use it, you just need to include a key called <key>NSLocationWhenInUseUsageDescription</key> in info.plist which is inside the ios/findCoordsApp directory.

1<?xml version="1.0" encoding="UTF-8"?>
2<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "">
3<plist version="1.0">
5 <key>CFBundleDevelopmentRegion</key>
6 <string>en</string>
7 <key>CFBundleDisplayName</key>
8 <string>findCoordsApp</string>
9 [..]
10 <key>NSLocationWhenInUseUsageDescription</key>
11 <string></string>
12 <key>NSAppTransportSecurity</key>
13 <!--See -->
14 [...]

For android, we need to add the following line in android/app/src/AndroidManifest.xml file.

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

Wrapping Up

Now if you run your application you will see the following screen.


Click on the text and you will be prompted to ask whether to allow the application to request for user’s location or not.


If you press allow, you will see the following result.


If you want to learn more about working with Geolocation API in a React Native application, please go through the official documentation.

Originally published at

I'm Aman working as an independent fullstack developer with technologies such as Node.js, ReactJS, and React Native. I try to document and write tutorials to help JavaScript, Web and Mobile developers.