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

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 = { ...

An introduction to Size Classes for Xcode 8

Introduction to Size Classes for Xcode In iOS 8, Apple introduced  size classes , a way to describe any device in any orientation. Size classes rely heavily on auto layout. Until iOS 8, you could escape auto layout. IN iOS8, Apple changed several UIKit classes to depend on size classes. Modal views, popovers, split views, and image assets directly use size classes to determine how to display an image. Identical code to present a popover on an iPad  causes a iPhone to present a modal view. Different Size Classes There are two sizes for size classes:  compact , and  regular . Sometime you’ll hear about any.  Any  is the generic size that works with anything. The default Xcode layout, is  width:any height:any . This layout is for all cases. The Horizontal and vertical dimensions are called  traits , and can be accessed in code from an instance of  UITraitCollection . The  compact  size descr...

What are the Alternatives of device UDID in iOS? - iOS7 / iOS 6 / iOS 5 – Get Device Unique Identifier UDID

Get Device Unique Identifier UDID Following code will help you to get the unique-device-identifier known as UDID. No matter what iOS user is using, you can get the UDID of the current iOS device by following code. - ( NSString *)UDID { NSString *uuidString = nil ; // get os version NSUInteger currentOSVersion = [[[[[UIDevice currentDevice ] systemVersion ] componentsSeparatedByString: @" . " ] objectAtIndex: 0 ] integerValue ]; if (currentOSVersion <= 5 ) { if ([[ NSUserDefaults standardUserDefaults ] valueForKey: @" udid " ]) { uuidString = [[ NSUserDefaults standardDefaults ] valueForKey: @" udid " ]; } else { CFUUIDRef uuidRef = CFUUIDCreate ( kCFAllocatorDefault ); uuidString = ( NSString *) CFBridgingRelease ( CFUUIDCreateString ( NULL ,uuidRef)); CFRelease (uuidRef); [[ NSUserDefaults standardUserDefaults ] setObject: uuidString ForKey: @" udid " ]; [[ NSUserDefaults standardUserDefaults ] synchro...