React Native Geolocation
This post will help you to get the current location using React Native Geolocation. React Native Geolocation provide the current location of the device in the form of Latitude and Longitude.
Let’s see how to use React Native Geolocation API to get the current location of any device/user. We will see how to import geolocation dependency, how to ask for permission to access the geolocation, and then code to get the geolocation in React Native.
Note: This example has been updated for React Native Version > 0.60 in which Geolocation has been moved to its new house @react-native-community/geolocation. So in this example, we will import that library to use Geolocation.
Code Snippet to use React Native GeoLocation
Geolocation.getCurrentPosition(
//Will give you the current location
(position) => {
//getting the Longitude from the location json
const currentLongitude =
JSON.stringify(position.coords.longitude);
//getting the Latitude from the location json
const currentLatitude =
JSON.stringify(position.coords.latitude);
}, (error) => alert(error.message), {
enableHighAccuracy: true, timeout: 20000, maximumAge: 1000
}
);
This example will get the Current Location Latitude and Longitude of the Device. This example will also show you how to ask for permission to get the current location. So let’s get started.
To Make a React Native App
Getting started with React Native will help you to know more about the way you can make a React Native project. We are going to use react native command line interface to make our React Native App.
If you have previously installed a global react-native-cli package, please remove it as it may cause unexpected issues:
npm uninstall -g react-native-cli @react-native-community/cli
Run the following commands to create a new React Native project
npx react-native init ProjectName
If you want to start a new project with a specific React Native version, you can use the --version argument:
npx react-native init ProjectName --version X.XX.X
Note If the above command is failing, you may have old version of react-native
or react-native-cli
installed globally on your pc. Try uninstalling the cli and run the cli using npx.
This will make a project structure with an index file named App.js in your project directory.
Installation of Dependency
To use Geolocation
we need to install @react-native-community/geolocation
dependency.
To install this open the terminal and jump into your project using
cd ProjectName
Run the following command to install
npm install @react-native-community/geolocation --save
This command will copy all the dependencies into your node_module directory.
CocoaPods Installation
Please use the following command to install CocoaPods
npx pod-install
Permission to use the Geolocation for Android
We are using a Native Location API so we need to add some permission to the AndroidManifest.xml
file. We are going to add the following permissions in the AndroidMnifest.xml
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION"
/>
Permission | Purpose |
---|---|
ACCESS_FINE_LOCATION | To access the Location Via GPS |
On devices before SDK version 23, the permissions are automatically granted if they appear in the manifest but after SDK version 23 we have to ask run time permission also, so we will ask for permission in code also. For more about the permission, you can see this post.
Permission to use the Geolocation for IOS
In IOS the necessary key in the Info.plist (Privacy – Location When in Use Usage Description) is already set when you create a new app. If you want to use a user’s location when the app is in the background you’ll have to do some additional configuration. You can find more details about different location permission from here. For now, there are three types of location permission and they are listed below.
If you have an idea about the permission then you can check it else please follow the instruction to add the permission in IOS. As we said you will find the already set location permission in IOS.
1. Open the project GeoLocationExample>ios>GeoLocationExample.xcodeproj in XCode. Click on Project (GeoLocationExample in my case) from the left sidebar and you will see multiple options in the workspace.
2. Select info tab which is info.plist. You can see “Privacy – Location When in Use Usage Description” is already there.
3. Add the value in front of that which will be visible when permission dialog pops up.
Code
Now Open App.js in any code editor and replace the code with the following code
App.js
// React Native Geolocation
// https://aboutreact.com/react-native-geolocation/
// import React in our code
import React, {useState, useEffect} from 'react';
// import all the components we are going to use
import {
SafeAreaView,
View,
Text,
StyleSheet,
Image,
PermissionsAndroid,
Platform,
Button,
} from 'react-native';
//import all the components we are going to use.
import Geolocation from '@react-native-community/geolocation';
const App = () => {
const [
currentLongitude,
setCurrentLongitude
] = useState('...');
const [
currentLatitude,
setCurrentLatitude
] = useState('...');
const [
locationStatus,
setLocationStatus
] = useState('');
useEffect(() => {
const requestLocationPermission = async () => {
if (Platform.OS === 'ios') {
getOneTimeLocation();
subscribeLocationLocation();
} else {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
title: 'Location Access Required',
message: 'This App needs to Access your location',
},
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
//To Check, If Permission is granted
getOneTimeLocation();
subscribeLocationLocation();
} else {
setLocationStatus('Permission Denied');
}
} catch (err) {
console.warn(err);
}
}
};
requestLocationPermission();
return () => {
Geolocation.clearWatch(watchID);
};
}, []);
const getOneTimeLocation = () => {
setLocationStatus('Getting Location ...');
Geolocation.getCurrentPosition(
//Will give you the current location
(position) => {
setLocationStatus('You are Here');
//getting the Longitude from the location json
const currentLongitude =
JSON.stringify(position.coords.longitude);
//getting the Latitude from the location json
const currentLatitude =
JSON.stringify(position.coords.latitude);
//Setting Longitude state
setCurrentLongitude(currentLongitude);
//Setting Longitude state
setCurrentLatitude(currentLatitude);
},
(error) => {
setLocationStatus(error.message);
},
{
enableHighAccuracy: false,
timeout: 30000,
maximumAge: 1000
},
);
};
const subscribeLocationLocation = () => {
watchID = Geolocation.watchPosition(
(position) => {
//Will give you the location on location change
setLocationStatus('You are Here');
console.log(position);
//getting the Longitude from the location json
const currentLongitude =
JSON.stringify(position.coords.longitude);
//getting the Latitude from the location json
const currentLatitude =
JSON.stringify(position.coords.latitude);
//Setting Longitude state
setCurrentLongitude(currentLongitude);
//Setting Latitude state
setCurrentLatitude(currentLatitude);
},
(error) => {
setLocationStatus(error.message);
},
{
enableHighAccuracy: false,
maximumAge: 1000
},
);
};
return (
<SafeAreaView style={{flex: 1}}>
<View style={styles.container}>
<View style={styles.container}>
<Image
source={{
uri:
'https://raw.githubusercontent.com/AboutReact/sampleresource/master/location.png',
}}
style={{width: 100, height: 100}}
/>
<Text style={styles.boldText}>
{locationStatus}
</Text>
<Text
style={{
justifyContent: 'center',
alignItems: 'center',
marginTop: 16,
}}>
Longitude: {currentLongitude}
</Text>
<Text
style={{
justifyContent: 'center',
alignItems: 'center',
marginTop: 16,
}}>
Latitude: {currentLatitude}
</Text>
<View style={{marginTop: 20}}>
<Button
title="Refresh"
onPress={getOneTimeLocation}
/>
</View>
</View>
<Text
style={{
fontSize: 18,
textAlign: 'center',
color: 'grey'
}}>
React Native Geolocation
</Text>
<Text
style={{
fontSize: 16,
textAlign: 'center',
color: 'grey'
}}>
www.aboutreact.com
</Text>
</View>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'white',
padding: 10,
alignItems: 'center',
justifyContent: 'center',
},
boldText: {
fontSize: 25,
color: 'red',
marginVertical: 16,
textAlign: 'center'
},
});
export default App;
To Run the React Native App
Open the terminal again and jump into your project using.
cd ProjectName
1. Start Metro Bundler
First, you will need to start Metro, the JavaScript bundler that ships with React Native. To start Metro bundler run following command:
npx react-native start
Once you start Metro Bundler it will run forever on your terminal until you close it. Let Metro Bundler run in its own terminal. Open a new terminal and run the application.
2. Start React Native Application
To run the project on an Android Virtual Device or on real debugging device:
npx react-native run-android
or on the iOS Simulator by running (macOS only)
npx react-native run-ios
Possible Error Reporting
While running iOS app you can see these 2 reporting which means @react-native-community/geolocation has some issue you can anytime downgrade the version to 2.0.2 which is stable and working
* Error: The package ‘@react-native-community/geolocation’ doesn’t seem to be linked. Make sure
* Property ‘sourceInformation’ not found on object of type ‘CLLocation’
Output Screenshots
Android
If you are using Android Emulator to run the app. You have to send the GPS location manually from the menu button (3 dots)
IOS
Output in Online Emulator
This is how you can Get the Current Location of the Device Using React Native Geolocation. If you have any doubts or you want to share something about the topic you can comment below or contact us here. There will be more posts coming soon. Stay tuned!
Hope you liked it. 🙂
when i give permission its not enable device location button. and i manually enabled the location button but the state is not updating automatically its not showing latitude and longitude
Hi Vinayak, Yes it will not enable the location automatically, permission is to take the GPS location not to enable it. Have you tried it out of the working area? I have also not received the location in my room and I have to move out as GPS will not connect under the roof.
how can i update the state when the device location is on???
With the help of getCurrentPosition you will get the current position and with the help of watchPosition you will get the updated position every time when it changes. So watchPosition will work as a listener to notify the location change.
Good Brother…
Is there any way or trick to get location when the app is in background or killed and also store it in the database every single second.
This works with app in background but will not work when app killed. In the Native applications I used alarm managers to awake the application after an interval but not sure with the React Native app.
For the location in every second point, Instead of getting the location in every second you can use Geolocation.watchPosition which will notify you whenever the location got updated so in this way you can consider that the location from last time to current update was same that will help you to reduce the redundant database entries.
how can we enable the location if it’s turned off??
You can use react-native-android-location-enabler. Also can see Asking to turn on location #86
sir please guide me that if we want to get location of any other device which have no app install then how can we get its location
Can we get address from this latitude and longitude.
You can use Google’s reverse geocoding API.
Please share proper example of that
you can use react-native-geocoder npm library and access the location name using lat long.
iam face problem whenever i run your code it is rn error it is show
@reactnative comunity/geolocation native.Rncgeolocation is null to fix this try this issuethis step
run react native link@react native community/geolocation in project
This comes when you have any permission issue, please have look at the permission section properly you will find the issue
Hii..sir when i used this library install successfully but “MaxBufferError: stderr maxBuffer exceeded” error shows .I cant find the root cause is there any solution for this error ..thank you
Is this allow app to fetch device location when device is locked ?