Newby Coder header banner

Device Location in React Native

Latitude Longitude of Current Location of Device can be retrieved in react native using Geolocation.watchPosition() method of react-native-geolocation-service package

For iOS react-native-location package can be used to get permission to access location from a user

That was kind of a work around

It can be omitted to check if permission can be requested using Geolocation of react-native-geolocation-service package, and used if not


Creating new React Native App

Check React Native Installation for installation related info

Use react-native init command to create a new React Native project (here named NcDeviceLocationApp)

react-native init NcDeviceLocationApp

This creates a directory named NcDeviceLocationApp and initializes it as a react native application directory

This can be skipped in case an existing react native project is being integrated into


Dependency

Go to project directory (here NcDeviceLocationApp)

cd NcDeviceLocationApp

Add @react-native-community/netinfo && react-native-location to current project using yarn

yarn add react-native-geolocation-service react-native-location

or using npm

npm install react-native-geolocation-service react-native-location --save

iOS

After yarn add command, cd into ios folder inside project directory

cd ios

Use pod command to install any required CocoaPods dependencies:

pod install

Permissions

Requesting permission to access location in Android

Find and open file_picker_app (project directory) β†’ android β†’ app β†’ src β†’ main β†’ AndroidManifest.xml

Add ACCESS_FINE_LOCATION permission (before <application tag)

file_picker_app/android/app/src/main/AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.file_picker_app">
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Requesting location permission in iOS

Geolocation is enabled by default when a project is created with react-native init

To check, find and open NcDeviceLocationApp (project directory) β†’ ios β†’ NcDeviceLocationApp (ios app name presumably same as project directory) β†’ Info.plist

Check if one of NSLocationWhenInUseUsageDescription, NSLocationAlwaysAndWhenInUseUsageDescription or NSLocationAlwaysUsageDescription is present

If not, then include NSLocationWhenInUseUsageDescription and NSLocationAlwaysAndWhenInUseUsageDescription to enable geolocation when using the app

NcDeviceLocationApp/ios/NcDeviceLocationApp/Info.plist
<key>NSLocationWhenInUseUsageDescription</key>
<string>Some message to appear in the prompt</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>Also can be empty</string>

Usage

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

Available methods

Example usage of to get current location coordinates:

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

componentDidMount() {
    Geolocation.getCurrentPosition(
        (position) => {
          console.log(position);
        },
        (error) => {
          console.log(error.code, error.message);
        },
        { enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 }
    );
}

App Code

ViewUser.js
import React, { Component } from 'react';
import { StyleSheet, Text, View, PermissionsAndroid, Alert, Platform } from 'react-native';
import Geolocation from 'react-native-geolocation-service';
import RNLocation from 'react-native-location';

//async function class to ask for runtime permission to access GPS location
export async function request_device_location_runtime_permission() {
  try {
    const granted = await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
      {
        'title': 'ReactNativeCode Location Permission',
        'message': 'ReactNativeCode App needs access to your location '
      }
    )
    if (granted === PermissionsAndroid.RESULTS.GRANTED) {
      Alert.alert("Location Permission Granted.");
    }
    else {
      Alert.alert("Location Permission Not Granted");
    }
  } catch (err) {
    console.warn(err)
  }
}

export default class Project extends Component {
  constructor(){
    super()
    this.state = {
      latitude : 0,
      longitude : 0,
      error : null
    }
  }

  // use Geolocation.watchPosition() method to access devices’s current latitude and longitude
  // watchPosition() method is supposed to get invoked when location changes
  async componentDidMount() {
    if(Platform.OS === 'android') {
        await request_device_location_runtime_permission();
    }
    else { 
        // Geolocation.requestAuthorization('whenInUse')
        await RNLocation.requestPermission({ ios:"whenInUse"}).then(granted => {
            console.log("ios permission granted?: ", granted);
        });
    }

    this.getLongLat = Geolocation.watchPosition(
      (position) => {
        this.setState({
          latitude: position.coords.latitude,
          longitude: position.coords.longitude,
          error: null,
        });
        console.log(position);
      },
      (error) => this.setState({ error: error.message }),
      { enableHighAccuracy: true, timeout: 2000, maximumAge: 100, distanceFilter: 10 },
    );
  }

  render() {
    return (
      <View style={styles.MainContainer}>
        <Text style={styles.text}> Latitude = {this.state.latitude}</Text>
        <Text style={styles.text}> Longitude = {this.state.longitude}</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  MainContainer: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: '#f5fcff',
    padding: 11

  },
  text:
  {
    fontSize: 22,
    color: '#000',
    textAlign: 'center',
    marginBottom: 10
  },
});

Run instructions

Running in Android

cd into project directory (here NcDeviceLocationApp)

cd NcDeviceLocationApp

Run metro server to serve js

react-native start

Go to project directory in another terminal tab

Enter following run command for Android:

react-native run-android
cl-react-native-device-location

Running in ios

cd into project directory (here NcDeviceLocationApp)

cd NcDeviceLocationApp

Enter following command :

react-native run-ios

This might take some time


If the app shows error about metro server not configured (check Running an App in iOS), then run metro server in another tab:

react-native start

Reload the app

Re-run react-native run-ios command if reloading doesn't work

cm-react-native-device-location-as1cm-react-native-device-location-as2