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

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

16 AWS Gotchas

16 AWS Gotchas In January I launched the MVP for my own startup,  Proximistyle , which helps you find what you’re looking for nearby. On advice from friends and industry contacts I chose AWS as my cloud provider. Having never had to set up my own cloud infrastructure before, the learning curve to get from no experience to a stable VPC system I was happy with was significantly steeper than expected, and had its fair share of surprises. #1 Take advantage of the free resources offered AWS offers a free tier for new accounts. If you have recently bought a domain and set up a company you qualify for the free tier for a year. Additionally, if you are a bootstrapped startup you can apply for  the Startup Builders package  and get $1000 in AWS credits. After doing the above, you’re now ready to get started with setting up the AWS infrastructure for your startup. #2 Set up billing budgets and alerting The very first thing you should do after setting up billing, is enabling a budge...

Ultimate Folder Structure For Your React Native Project

  Ultimate Folder Structure For Your React Native Project React native project structure React Native is a flexible framework, giving developers the freedom to choose their code structure. However, this can be a double-edged sword for beginners. Though it offers ease of coding, it can soon become challenging to manage as your project expands. Thus, a structured folder system can be beneficial in many ways like better organization, simplified module management, adhering to coding practices, and giving a professional touch to your project. This write-up discusses a version of a folder arrangement that I employ in my React Native projects. This structure is based on best practices and can be modified to suit the specific needs of your project. Before we get into the project structure let’s give credit to @sanjay who has the original idea of the structure but I modify his version of the code, to make it better. Base library axios  — For network calling. react-navigation ...