Skip to main content

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.
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 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> in AndroidManifest.xml file.
The Android API >=23 requires to request the ACCESS_FINE_LOCATION permission using the PermissionsAndroid API.

Methods of Geolocation

MethodDescription
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


  1. import React from 'react';  
  2. import { StyleSheet,Platform, Text, View } from 'react-native';  
  3.   
  4. export default class App extends React.Component {  
  5.     constructor(){  
  6.         super();  
  7.         this.state = {  
  8.             ready: false,  
  9.             where: {lat:null, lng:null},  
  10.             error: null  
  11.         }  
  12.     }  
  13.     componentDidMount(){  
  14.         let geoOptions = {  
  15.             enableHighAccuracy:false,  
  16.             timeOut: 20000//20 second  
  17.           //  maximumAge: 1000 //1 second  
  18.         };  
  19.         this.setState({ready:false, error: null });  
  20.         navigator.geolocation.getCurrentPosition( this.geoSuccess,  
  21.             this.geoFailure,  
  22.             geoOptions);  
  23.     }  
  24.     geoSuccess = (position) => {  
  25.         console.log(position.coords.latitude);  
  26.   
  27.         this.setState({  
  28.             ready:true,  
  29.             where: {lat: position.coords.latitude,lng:position.coords.longitude }  
  30.         })  
  31.     }  
  32.     geoFailure = (err) => {  
  33.         this.setState({error: err.message});  
  34.     }  
  35.     render() {  
  36.         return (  
  37.             <View style={styles.container}>  
  38.                 { !this.state.ready && (  
  39.                     <Text style={styles.big}>Using Geolocation in React Native.</Text>  
  40.                 )}  
  41.                 { this.state.error && (  
  42.                     <Text style={styles.big}>Error: {this.state.error}</Text>  
  43.                 )}  
  44.                 { this.state.ready && (  
  45.                     <Text style={styles.big}>  
  46.                         Latitude: {this.state.where.lat}  
  47.                         Longitude: {this.state.where.lng}  
  48.                     </Text>  
  49.                 )}  
  50.             </View>  
  51.         );  
  52.     }  
  53. }  
  54.   
  55. const styles = StyleSheet.create({  
  56.     container: {  
  57.         flex: 1,  
  58.         backgroundColor: '#fff',  
  59.         alignItems: 'center',  
  60.         justifyContent: 'center'  
  61.     },  
  62.     big: {  
  63.         fontSize: 25  
  64.     }  
  65. });  

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).

Comments

Popular Posts

How I Reduced the Size of My React Native App by 85%

How and Why You Should Do It I borrowed 25$ from my friend to start a Play Store Developer account to put up my first app. I had already created the app, created the assets and published it in the store. Nobody wants to download a todo list app that costs 25mb of bandwidth and another 25 MB of storage space. So today I am going to share with you how I reduced the size of Tet from 25 MB to around 3.5 MB. Size Matters Like any beginner, I wrote my app using Expo, the awesome React Native platform that makes creating native apps a breeze. There is no native setup, you write javascript and Expo builds the binaries for you. I love everything about Expo except the size of the binaries. Each binary weighs around 25 MB regardless of your app. So the first thing I did was to migrate my existing Expo app to React Native. Migrating to React Native react-native init  a new project with the same name Copy the  source  files over from Expo project Install all de...

How to recover data of your Android KeyStore?

These methods can save you by recovering Key Alias and Key Password and KeyStore Password. This dialog becomes trouble to you? You should always keep the keystore file safe as you will not be able to update your previously uploaded APKs on PlayStore. It always need same keystore file for every version releases. But it’s even worse when you have KeyStore file and you forget any credentials shown in above box. But Good thing is you can recover them with certain tricks [Yes, there are always ways]. So let’s get straight to those ways. 1. Check your log files → For  windows  users, Go to windows file explorer C://Users/your PC name/.AndroidStudio1.4 ( your android studio version )\system\log\idea.log.1 ( or any old log number ) Open your log file in Notepad++ or Any text editor, and search for: android.injected.signing and if you are lucky enough then you will start seeing these. Pandroid.injected.signing.store.file = This is  file path where t...

React Native - Text Input

In this chapter, we will show you how to work with  TextInput  elements in React Native. The Home component will import and render inputs. App.js import React from 'react' ; import Inputs from './inputs.js' const App = () => { return ( < Inputs /> ) } export default App Inputs We will define the initial state. After defining the initial state, we will create the  handleEmail  and the  handlePassword  functions. These functions are used for updating state. The  login()  function will just alert the current value of the state. We will also add some other properties to text inputs to disable auto capitalisation, remove the bottom border on Android devices and set a placeholder. inputs.js import React , { Component } from 'react' import { View , Text , TouchableOpacity , TextInput , StyleSheet } from 'react-native' class Inputs extends Component { state = { ...