Dark Mode
Image

React Native Geolocation

The Geolocation API is used to get the geographical position (latitude and longitude) of a place. It extends the Geolocation web specification. This API is available through the navigator.geolocation globally, so that we do not need to import it.

In Android, Geolocation API uses android.location API. However, this API is not recommended by Google because it is less accurate, and slower than the recommended Google Location Services API. To use the Google Location Services API in React Native, use the react-native-geolocation-service module.

React Native Configuration and Permissions

In this section, we discuss the project which is created using react-native init or with expo init or Create React Native App.

iOS

For iOS platform we include the NSLocationWhenInUseUsageDescription key in Info.plist to enable geolocation. Geolocation is by default enabled when a project is created with react-native init.

PauseNext

Unmute

Current Time 0:00

/

Duration 18:10

Loaded: 1.84%

 

Fullscreen.

To enable the geolocation in background, we need to include the 'NSLocationAlwaysUsageDescription' key in Info.plist. This requires adding location as a background mode in the 'Capabilities' tab in Xcode.

Android

To access the location in Android, we need to add  in AndroidManifest.xml file.

The Android API >=23 requires to request the ACCESS_FINE_LOCATION permission using the PermissionsAndroid API.

Methods of Geolocation

Method Description
getCurrentPosition() It invokes the success callback once with latest location information.
watchPosition() It invokes the success callback whenever the location changes. It returns a watchId (number).
clearWatch() It clears the watchId of watchPosition().
stopObserving() It stops observing for device location changes as well as it removes all listeners previously registered.
setRNConfiguration() It sets the configuration options, which is used in all location requests.
requestAuthorization() It requests suitable Location permission based on the key configured on pList.

React Native Geolocation Example

App.js

import React from 'react';  
import { StyleSheet,Platform, Text, View } from 'react-native';  
  
export default class App 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}>  
                { !this.state.ready && (  
                    <Text style={styles.big}>Using Geolocation in React Native.</Text>  
                )}  
                { this.state.error && (  
                    <Text style={styles.big}>Error: {this.state.error}</Text>  
                )}  
                { this.state.ready && (  
                    <Text style={styles.big}>  
                        Latitude: {this.state.where.lat}  
                        Longitude: {this.state.where.lng}  
                    </Text>  
                )}  
            </View>  
        );  
    }  
}  
  
const styles = StyleSheet.create({  
    container: {  
        flex: 1,  
        backgroundColor: '#fff',  
        alignItems: 'center',  
        justifyContent: 'center'  
    },  
    big: {  
        fontSize: 25  
    }  
});  

Output:

React Native Geolocation

Note: We run the above code on Android Emulator, it has not GPS enabled. The latitude and longitude values are read from Emulator Extended controls (default value).

Comment / Reply From