Table of contents
1.
Introduction
2.
Configurations and Permissions for Geolocation
2.1.
Permissions in iOS
2.2.
Permissions in Android
3.
Methods of Geolocation
3.1.
watchPosition() 
3.2.
clearWatch() 
3.3.
stopObserving() 
3.4.
getCurrentPosition()
3.5.
setRNConfiguration()
3.6.
requestAuthorization() 
4.
Example using Geolocation
5.
Frequently Asked Questions
5.1.
What is the work of StyleSheet in react-native?
5.2.
What is the use of the render() function in react-native?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Geolocation in React Native

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

The capacity to determine the geographic location of a device connected to the internet is known as geolocation. The user must typically provide permission for an app to access their location data. The Geolocation API determines a location's geographic position (latitude and longitude). It adds to the Geolocation web standard. The navigator provides access to this API. We don't need to import geolocation because it's global.

Google recommended geolocation API is Google Location Service API. To integrate it with react-native, we use the react-native-geolocation-service module.

Click on the following link to read further: Hooks in React JS

Configurations and Permissions for Geolocation

To use the geolocation in your app, you need to first make the required configuration for both android and iOS. We also need to get permission for the app to use the user's location.

Permissions in iOS

To enable geolocation when using the app, include the NSLocationWhenInUseUsageDescription key in Info.plist. When you use react-native init to start a project, geolocation is enabled by default.

You must include the 'NSLocationAlwaysUsageDescription' key in Info.plist and add location as a background mode in the 'Capabilities' tab in Xcode to enable geolocation in the background.

Ensure the RCTGeolocation sub-podspec is included if you're using CocoaPods for React Native.

Permissions in Android

You must have to add the following line to your AndroidManifest.xml to request location access:

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


Android API 23 or greater Use the PermissionsAndroid API to check for and request the ACCESS FINE LOCATION permission. Failure in this may result in a severe app crash.

Methods of Geolocation

To use the services provided by the geolocation class in react-native, it provides us with several methods such as:

watchPosition() 

It invokes a callback name success when the location changes and returns a watchId.

Syntax:

geolocation.watchPosition(success, [error], [options]);


Parameters:

  • success: It gets invoked whenever the location changes.
  • error: It gets invoked whenever an error is encountered.
  • To know about its other parameters, go to the official documentation.

clearWatch() 

It is used to clear the watchId of the watchPosition().

Syntax:

geolocation.clearWatch(watchID);


Parameters:

  • watchId: This is the id returned by the watchPosition() method.

stopObserving() 

It will stop observing the device's location changes and remove previously registered listeners.

getCurrentPosition()

It calls the success callback once with the most recent location data.

Syntax:

geolocation.getCurrentPosition(
  geo_success,
  [geo_error],
  [geo_options]
);


Parameters:

  • geo_success: It gets the value of the latest location information.
  • geo_error: This is invoked when an error occurs.
  • To know about its other parameters, go to the official documentation.

setRNConfiguration()

 It is used to set the configuration option in all requested locations.

Syntax:

geolocation.setRNConfiguration(config);


Parameter:

  • config: If this is true, you need to request permissions before using geolocation APIs.

requestAuthorization() 

Based on the key set on plist, request appropriate Location permission. It will request Always authorization if NSLocationAlwaysUsageDescription is specified but request InUse authorization if NSLocationWhenInUseUsageDescription is set.

Syntax:

geolocation.requestAuthorization(); 

Example using Geolocation

We've had enough theories let's consider an example to get a good grasp on the geolocation APIs. In this example, we are about to create a simple screen in the App.js file with the heading "Geolocation Demo", as our react-native code will run, it will ask for the device's location permission. After granting the permission, it will show the latitude and longitude of the device's location.

App.js file

Code:

import React from 'react';  
import { StyleSheet,Platform, Text, View, ActivityIndicator, Button } from 'react-native'; 
  
export default class GeolocationDemo extends React.Component {  
    constructor(){  
        super();  
        this.state = {  
            ready: false,  
            where: {lat:null, lng:null},  
            error: null  
        }  
    }  
    componentDidMount(){  
        let geoOptions = {  
            enableHighAccuracy:false,  
            timeOut: 20000, //20 second  
          //  maximumAge: 1000 //1 second  
        };  
        this.setState({ready:false, error: null });  
        navigator.geolocation.getCurrentPosition( this.geoSuccess,  
            this.geoFailure,  
            geoOptions);  
    }  
    geoSuccess = (position) => {  
        console.log(position.coords.latitude);  
  
        this.setState({  
            ready:true,  
            where: {lat: position.coords.latitude,lng:position.coords.longitude }  
        })  
    }  
    geoFailure = (err) => {  
        this.setState({error: err.message});  
    }  
    render() {  
        return (  
            <View style={styles.container}>  
                <Text style={styles.heading}>Geolocation Demo</Text>
                      
                { !this.state.ready && (  
                    //<Text style={styles.big}>Using Geolocation in React Native.</Text>
                    <ActivityIndicator style= {styles.loader} size="large" color="red" />  
                )}  
                { this.state.error && (  
                    <Text style={styles.error}>Error: {this.state.error}</Text>  
                )}  
                { this.state.ready && (  
                    <Text style={styles.result}>  
                        Latitude: {this.state.where.lat}{'\n'}  
                        Longitude: {this.state.where.lng}  
                    </Text>
                      
                )}
                <View style={styles.bottomText}>
                  <Text>
                  <Text style={styles.bottomText1}>code</Text>
                  <Text style={styles.bottomText2}>studio</Text>
                  </Text>
                  <Text>Powered By</Text>
                  <Text style={styles.bottomText3}>Coding Ninjas</Text>
                </View>
            </View>  
        );  
    }  
}  
  
const styles = StyleSheet.create({  
    container: {  
        flex: 1,  
        backgroundColor: 'teal',  
        alignItems: 'center',  
        justifyContent: 'center'  
    }, 
    heading: { 
        flex: 1,
        fontSize: 25,
        fontWeight: 'bold',
        justifyContent: 'top',
        textAlign: 'center',
        marginTop: 30,  
    },
    result: { 
      flex:1, 
        fontSize: 20,
        textAlign: 'center',  
    },
    loader: {
      flex: 2,
    }, 
    error: {
      flex: 2,
      fontSize: 15,
    },
    bottomText: {
      marginBottom:30,
      textAlign: 'center',
      alignItems: 'center'
    },
    bottomText1: {
      fontSize: 25,
      fontWeight: 'bold',    
    },
    bottomText2: {
      fontSize: 25,
    },
    bottomText3: {
      fontWeight: 'bold',
      color: 'orange'
    }
});  


Output:

 

 

Explanation:

As we start the app first, it will ask for the location's permission. While waiting for the permission, there will be an activity indicator in the center, as the GeolocationDemo class gets the permission and finds the location coordinates, the latitude and longitude values replace the activity indicator. In your virtual device, you might not see your current location because its location is set to a different location. You can choose your location by clicking on the more (at the bottom in the right options panel) option, going to the location tab, searching your location, and clicking on the savepoints to save your coordinates. Your points will get added to the window on the right, select your savepoints and click on the Set location button. 

Also see,  React Native Reanimated

Frequently Asked Questions

What is the work of StyleSheet in react-native?

React Native StyleSheet is a technique for customizing an application with JavaScript code. Its primary use is to style and structure components in an application.

What is the use of the render() function in react-native?

The render function in React is used to render HTML to a web page (). The objective of the method is to display the provided HTML code within the specified HTML element. We can read props and states in the render() method and deliver our JSX code to the app's root component.

How Linking is used in react-native?

Linking allows you to engage with both incoming and outgoing app links from a single interface. In the example illustrated above, we have used the linking for outgoing app links.

Conclusion

In this article, we've extensively discussed Geolocation in React Native. We've discussed its methods and its parameters, along with an example.
We hope this blog has helped you enrich your knowledge regarding Geolocation in React Native. Do check out the awesome content on the Coding Ninjas Website, Android DevelopmentCoding Ninjas Studio Interview BundleCoding Ninjas Studio Interview ExperiencesCoding Ninjas Studio ContestsCoding Ninjas CoursesCoding Ninjas Studio Problems, and Coding Ninjas Studio Test SeriesDo not forget to upvote our blog to help other ninjas grow. 
Happy Coding!

Live masterclass