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

Reloading UITableView while Animating Scroll in iOS 11

Reloading UITableView while Animating Scroll Calling  reloadData  on  UITableView  may not be the most efficient way to update your cells, but sometimes it’s easier to ensure the data you are storing is in sync with what your  UITableView  is showing. In iOS 10  reloadData  could be called at any time and it would not affect the scrolling UI of  UITableView . However, in iOS 11 calling  reloadData  while your  UITableView  is animating scrolling causes the  UITableView  to stop its scroll animation and not complete. We noticed this is only true for scroll animations triggered via one of the  UITableView  methods (such as  scrollToRow(at:at:animated:) ) and not for scroll animations caused by user interaction. This can be an issue when server responses trigger a  reloadData  call since they can happen at any moment, possibly when scroll animation is occurring. Example of s...

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

Xcode & Instruments: Measuring Launch time, CPU Usage, Memory Leaks, Energy Impact and Frame Rate

When you’re developing applications for modern mobile devices, it’s vital that you consider the performance footprint that it has on older devices and in less than ideal network conditions. Fortunately Apple provides several powerful tools that enable Engineers to measure, investigate and understand the different performance characteristics of an application running on an iOS device. Recently I spent some time with these tools working to better understand the performance characteristics of an eCommerce application and finding ways that we can optimise the experience for our users. We realised that applications that are increasingly performance intensive, consume excessive amounts of memory, drain battery life and feel uncomfortably slow are less likely to retain users. With the release of iOS 12.0 it’s easier than ever for users to find applications that are consuming the most of their device’s finite amount of resources. Users can now make informed decisions abou...