How to use React Native Geolocation Service?
You may have questioned how ride-hailing and food delivery services determine your current location. Ever come across the term Geolocation?
We’ll learn how to use geolocation in React Native in this tutorial. We’ll create an example application that allows the user to submit their position to another source, such as Twitter, and shows their location on a map with longitude and latitude data.
What is geolocation?
The ability to determine a device’s geographic location to the internet is known as geolocation. Using a device’s IP address to find its location in terms of nation, city, or postal code is a basic example of geolocation. Most of the time, an app cannot access a user’s location data without the user’s consent.
Geolocation in React Native
The @react-native-community/geolocation API for geolocation is made available by React Native. However, because the React Native API is slower and less precise than the suggested Google Location Services API, Google does not advise using it for geolocation.
React Native geolocation services can now be easily implemented in React Native thanks to the wonderful libraries created by the React Native community, such as react-native-location and react-native-geolocation-service.
We’ll be using the react-native-geolocation-service library in this React Native geolocation tutorial; it’s accessible as a Node package on npm.
Our program will be able to perform the following tasks:
- Requests authorization to access location information on your iOS and Android smartphone.
- Select the coordinates of your location.
- Retains or transmits your position data
Execute the following code to find out your Node.js version:
$ node -v
// returns node version
Multiple Node.js versions installed on your computer may be managed with nvm. You may create a new project using the integrated command line interface of React Native app development framework. It may be accessed with npx, which comes with Node.js, without requiring any global installations.
Initialize a React Native project
Enter the following command into your terminal to get started:
$ npx ReactNativeGeolocation init React Native app development.
You may execute Node-based dependencies in your terminal without installing them on your computer by using the Node-based command npx.
The directive to create a new React Native project using ReactNativeLocation as the location where the project files will be installed is contained in the init portion of the command.
It is not necessary to install React Native development services on your computer in order to use the npx react-native command. As an alternative, you may use npx to execute React Native instructions by installing React Native globally on your computer. Use this command to install React Native globally:
$ npm install -g react-native-cli
Next, you can use the following command to verify that React Native is installed:
$react-native -v
The aforementioned program outputs to the console the installed version of React Native on your system. Navigate to the ReactNativeGeolocation directory using your preferred IDE.
The React Native app has been configured for us by the command we performed to begin the project.
All of our code will be written in the App.js file. To execute the instructions, make sure you are in your application’s root directory.
Launching Metro is the first step. React Native comes with a JavaScript bundler called Metro. Metro generates a single JavaScript file with all of your code and its dependencies after receiving an entry file and several options:
$ npx react-native start
Open a new terminal and type the following command while Metro is running in your current terminal:
$npx run-android react-native
You’ll need an Android emulator or a mobile device in debug mode connected to your PC to launch the app. However, the following causes might cause an error if you’re using the emulator in Android Studio:
An ANDROID_HOME environment variable that links to the SDK directory must be defined.
You must accept every SDK license.
The screen that appears next should be as follows:
We are now able to modify the application within our App.js folder. Take out all of the outdated code from App.js and replace it with this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
/** * Sample React Native App * https://github.com/facebook/react-native * * @format * @flow strict-local */ import React from 'react'; import {StyleSheet, View, Text} from 'react-native'; const App = () => { return ( <View style={styles.container}> <Text>Welcome!</Text> </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', alignItems: 'center', justifyContent: 'center', }, }); export default App; |
The code above opens a new window for us to write our application on:
React Native requirements needed for geolocation
Using Yarn or npm, install the react-native-geolocation-service library using the corresponding commands below:
React-native-geolocation-service is added with yarn.
React-native-geolocation-service –save may be installed with npm.
Previously, linking the library was required; however, in more recent iterations of React Native app development services, this process is automated when executing a build using npx react-native run-android, or its iOS counterpart.
These connecting instructions should assist you in setting up React Native ≤v0.60.
In addition, we want to confirm that we include the following code to android/src/main/AndroidManifest.xml to allow permissions in the application:
Android:name=”android.permission.INTERNET” />
Run npx react-native run-android once more after that.
React Native application geolocation integration
Let’s add two buttons to our React Native app: one to communicate the user’s location to Twitter and another to get the user’s location, which we’ll keep in the app state.
Update the React Native imports to include Button, for example, import {StyleSheet, View, Text, Button} from’react-native’;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
// Function to get permission for location const requestLocationPermission = async () => { try { const granted = await PermissionsAndroid.request( PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION, { title: 'Geolocation Permission', message: 'Can we access your location?', buttonNeutral: 'Ask Me Later', buttonNegative: 'Cancel', buttonPositive: 'OK', }, ); console.log('granted', granted); if (granted === 'granted') { console.log('You can use Geolocation'); return true; } else { console.log('You cannot use Geolocation'); return false; } } catch (err) { return false; } }; |
You may try this unified iOS/Android permissions library or read articles on iOS permission flow for information on iOS app permissions.
To ask the issuer for authorization, we call the request function in the code above.
Next, we supply an object containing the prompt’s information. We return true if the request was successful and false otherwise.
Obtaining the user’s location information
We will now establish a state to monitor our users’ whereabouts from within our component.
1 2 3 |
// state to hold location const [location, setLocation] = useState(false); |
Next, we’ll create a function that will ask for permission when the GET LOCATION button is touched. If authorization is given, the user’s current location will be obtained:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
// function to check permissions and get Location const getLocation = () => { const result = requestLocationPermission(); result.then(res => { console.log('res is:', res); if (res) { Geolocation.getCurrentPosition( position => { console.log(position); setLocation(position); }, error => { // See error code charts below. console.log(error.code, error.message); setLocation(false); }, {enableHighAccuracy: true, timeout: 15000, maximumAge: 10000}, ); } }); console.log(location); }; |
We observe ourselves calling the previously written requestLocationPermission function, which returns a promise that can resolve to yes or false. We use the react-native-geolocation-service library to obtain the precise position and set the location state to the result if the promise resolves to true. It will set the location state to false if the promise is false, indicating that authorization was not granted, or if it is unable to obtain the location.
Next, we add the getLocation method to the GET LOCATION button as an onPress event:
1 |
<Button title="Get Location" onPress={getLocation} /> |
As of right now, your App.js code ought to resemble this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 |
/** * Sample React Native App * https://github.com/facebook/react-native * * @format * @flow strict-local */ import React, {useState, useEffect} from 'react'; import {StyleSheet, View, Text, Button, PermissionsAndroid} from 'react-native'; import Geolocation from 'react-native-geolocation-service'; // Function to get permission for location const requestLocationPermission = async () => { try { const granted = await PermissionsAndroid.request( PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION, { title: 'Geolocation Permission', message: 'Can we access your location?', buttonNeutral: 'Ask Me Later', buttonNegative: 'Cancel', buttonPositive: 'OK', }, ); console.log('granted', granted); if (granted === 'granted') { console.log('You can use Geolocation'); return true; } else { console.log('You cannot use Geolocation'); return false; } } catch (err) { return false; } }; const App = () => { // state to hold location const [location, setLocation] = useState(false); // function to check permissions and get Location const getLocation = () => { const result = requestLocationPermission(); result.then(res => { console.log('res is:', res); if (res) { Geolocation.getCurrentPosition( position => { console.log(position); setLocation(position); }, error => { // See error code charts below. console.log(error.code, error.message); setLocation(false); }, {enableHighAccuracy: true, timeout: 15000, maximumAge: 10000}, ); } }); console.log(location); }; return ( <View style={styles.container}> <Text>Welcome!</Text> <View style={{marginTop: 10, padding: 10, borderRadius: 10, width: '40%'}}> <Button title="Get Location" onPress={getLocation} /> </View> <Text>Latitude: {location ? location.coords.latitude : null}</Text> <Text>Longitude: {location ? location.coords.longitude : null}</Text> <View style={{marginTop: 10, padding: 10, borderRadius: 10, width: '40%'}}> <Button title="Send Location" /> </View> </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', alignItems: 'center', justifyContent: 'center', }, }); export default App; |
When it launches and you select the GET LOCATION button, the following pop-up window will appear:
After that, the screen ought to display your location as seen below:
The Location Entity
React-native-geolocation-service will provide a location object that resembles the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
{ "coords": { "accuracy": 5, "altitude": 5, "altitudeAccuracy": 0.5, "heading": 0, "latitude": 37.4219983, "longitude": -122.084, "speed": 0 }, "mocked": false, "provider": "fused", "timestamp": 1662837540458 } |
Geolocation data transmission in React Native
We only need to change the communicate LOCATION button into a Tweet button to communicate the user’s geolocation data to Twitter.
We’ll show the data returned in the example before sending the user the location. Add the useState Hook from React to our project in the following way to do this:
1 |
import React, { useState } from 'react'; |
Then, under our App function, we define a state:
1 |
useState([]) = [viewLocation, isViewLocation] |
We call the isViewLocation function and update the viewLocation array with the location information object by updating the if expression as follows:
isViewLocation(reference)
Update the Location and Longitude text tags to see the information returned:
1 |
Longitude: {viewLocation.longitude} Latitude: {viewLocation.latitude} |
viewLocation.The function isViewLocation calls the object response, and latitude returns the latitude in that response. For the longitude, the same holds.
We may now update the button to notify Twitter of the user’s location. Below is a screenshot of our last sample application:
Send User Location Data to Twitter
Next, ask your mobile app development company to configure and include the user’s location in a new Tweet using the SEND LOCATION button:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
// Function to Send Location to twitter const sendLocation = () => { try { if (location) { const tweet = `latitude is ${location.coords.latitude} and longitude is ${location.coords.longitude}`; const url = `https://twitter.com/intent/tweet?text=${tweet}`; Linking.openURL(url); } } catch (error) { console.log(error); } }; |
The aforementioned function
- Determines if our location is in our state.
- Location will equal false if we don’t.
- Creates a string containing our latitude and longitude to serve as our tweet.
- Builds a URL to generate the tweet.
- Opens the URL by using the Linking object.
- Link & Import from React Native
You should now see a browser window that resembles the following image when you click the SEND LOCATION button:
The following code should be present in the final App.js file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 |
/** * Sample React Native App * https://github.com/facebook/react-native * * @format * @flow strict-local */ import React, {useState, useEffect} from 'react'; import { StyleSheet, View, Text, Button, PermissionsAndroid, Linking, } from 'react-native'; import Geolocation from 'react-native-geolocation-service'; // Function to get permission for location const requestLocationPermission = async () => { try { const granted = await PermissionsAndroid.request( PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION, { title: 'Geolocation Permission', message: 'Can we access your location?', buttonNeutral: 'Ask Me Later', buttonNegative: 'Cancel', buttonPositive: 'OK', }, ); console.log('granted', granted); if (granted === 'granted') { console.log('You can use Geolocation'); return true; } else { console.log('You cannot use Geolocation'); return false; } } catch (err) { return false; } }; const App = () => { // state to hold location const [location, setLocation] = useState(false); // function to check permissions and get Location const getLocation = () => { const result = requestLocationPermission(); result.then(res => { console.log('res is:', res); if (res) { Geolocation.getCurrentPosition( position => { console.log(position); setLocation(position); }, error => { // See error code charts below. console.log(error.code, error.message); setLocation(false); }, {enableHighAccuracy: true, timeout: 15000, maximumAge: 10000}, ); } }); console.log(location); }; // Function to Send Location to twitter const sendLocation = () => { try { if (location) { const tweet = `latitude is ${location.coords.latitude} and longitude is ${location.coords.longitude}`; const url = `https://twitter.com/intent/tweet?text=${tweet}`; Linking.openURL(url); } } catch (error) { console.log(error); } }; return ( <View style={styles.container}> <Text>Welcome!</Text> <View style={{marginTop: 10, padding: 10, borderRadius: 10, width: '40%'}}> <Button title="Get Location" onPress={getLocation} /> </View> <Text>Latitude: {location ? location.coords.latitude : null}</Text> <Text>Longitude: {location ? location.coords.longitude : null}</Text> <View style={{marginTop: 10, padding: 10, borderRadius: 10, width: '40%'}}> <Button title="Send Location" onPress={sendLocation} /> </View> </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', alignItems: 'center', justifyContent: 'center', }, }); export default App; |
Conclusion
There’s much more you can do with the location of a user now that you know how to get it. You may create an emergency button alert system, track a user, and even create a delivery service. There are countless options. We just touched the surface of the react-native-geolocation-service library in this tutorial, which we used to create our sample application.
If you’re looking for a user-friendly solution that provides precise location data on a website instead of a mobile app then you can explore
https://iplocation.io/my-location for seamless location viewing in a browser.
The characteristics of geolocation are intriguing and have many practical applications. If you intend to utilize geolocation in your React Native project, let us know in the comments. Have fun with coding!
Hire DianApps app developers to use the geolocation service in your business so that people can find you in a better and more efficient way.