Methods of Geolocation
To use the services provided by the geolocation class in react-native, it provides us with several methods such as:
watchPosition()
It invokes a callback name success when the location changes and returns a watchId.
Syntax:
geolocation.watchPosition(success, [error], [options]);
Parameters:
- success: It gets invoked whenever the location changes.
- error: It gets invoked whenever an error is encountered.
-
To know about its other parameters, go to the official documentation.
clearWatch()
It is used to clear the watchId of the watchPosition().
Syntax:
geolocation.clearWatch(watchID);
Parameters:
- watchId: This is the id returned by the watchPosition() method.
stopObserving()
It will stop observing the device's location changes and remove previously registered listeners.
getCurrentPosition()
It calls the success callback once with the most recent location data.
Syntax:
geolocation.getCurrentPosition(
geo_success,
[geo_error],
[geo_options]
);
Parameters:
- geo_success: It gets the value of the latest location information.
- geo_error: This is invoked when an error occurs.
-
To know about its other parameters, go to the official documentation.
setRNConfiguration()
It is used to set the configuration option in all requested locations.
Syntax:
geolocation.setRNConfiguration(config);
Parameter:
- config: If this is true, you need to request permissions before using geolocation APIs.
requestAuthorization()
Based on the key set on plist, request appropriate Location permission. It will request Always authorization if NSLocationAlwaysUsageDescription is specified but request InUse authorization if NSLocationWhenInUseUsageDescription is set.
Syntax:
geolocation.requestAuthorization();
Example using Geolocation
We've had enough theories let's consider an example to get a good grasp on the geolocation APIs. In this example, we are about to create a simple screen in the App.js file with the heading "Geolocation Demo", as our react-native code will run, it will ask for the device's location permission. After granting the permission, it will show the latitude and longitude of the device's location.
App.js file
Code:
import React from 'react';
import { StyleSheet,Platform, Text, View, ActivityIndicator, Button } from 'react-native';
export default class GeolocationDemo extends React.Component {
constructor(){
super();
this.state = {
ready: false,
where: {lat:null, lng:null},
error: null
}
}
componentDidMount(){
let geoOptions = {
enableHighAccuracy:false,
timeOut: 20000, //20 second
// maximumAge: 1000 //1 second
};
this.setState({ready:false, error: null });
navigator.geolocation.getCurrentPosition( this.geoSuccess,
this.geoFailure,
geoOptions);
}
geoSuccess = (position) => {
console.log(position.coords.latitude);
this.setState({
ready:true,
where: {lat: position.coords.latitude,lng:position.coords.longitude }
})
}
geoFailure = (err) => {
this.setState({error: err.message});
}
render() {
return (
<View style={styles.container}>
<Text style={styles.heading}>Geolocation Demo</Text>
{ !this.state.ready && (
//<Text style={styles.big}>Using Geolocation in React Native.</Text>
<ActivityIndicator style= {styles.loader} size="large" color="red" />
)}
{ this.state.error && (
<Text style={styles.error}>Error: {this.state.error}</Text>
)}
{ this.state.ready && (
<Text style={styles.result}>
Latitude: {this.state.where.lat}{'\n'}
Longitude: {this.state.where.lng}
</Text>
)}
<View style={styles.bottomText}>
<Text>
<Text style={styles.bottomText1}>code</Text>
<Text style={styles.bottomText2}>studio</Text>
</Text>
<Text>Powered By</Text>
<Text style={styles.bottomText3}>Coding Ninjas</Text>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'teal',
alignItems: 'center',
justifyContent: 'center'
},
heading: {
flex: 1,
fontSize: 25,
fontWeight: 'bold',
justifyContent: 'top',
textAlign: 'center',
marginTop: 30,
},
result: {
flex:1,
fontSize: 20,
textAlign: 'center',
},
loader: {
flex: 2,
},
error: {
flex: 2,
fontSize: 15,
},
bottomText: {
marginBottom:30,
textAlign: 'center',
alignItems: 'center'
},
bottomText1: {
fontSize: 25,
fontWeight: 'bold',
},
bottomText2: {
fontSize: 25,
},
bottomText3: {
fontWeight: 'bold',
color: 'orange'
}
});
Output:
Explanation:
As we start the app first, it will ask for the location's permission. While waiting for the permission, there will be an activity indicator in the center, as the GeolocationDemo class gets the permission and finds the location coordinates, the latitude and longitude values replace the activity indicator. In your virtual device, you might not see your current location because its location is set to a different location. You can choose your location by clicking on the more (at the bottom in the right options panel) option, going to the location tab, searching your location, and clicking on the savepoints to save your coordinates. Your points will get added to the window on the right, select your savepoints and click on the Set location button.
Also see, React Native Reanimated
Frequently Asked Questions
What is the work of StyleSheet in react-native?
React Native StyleSheet is a technique for customizing an application with JavaScript code. Its primary use is to style and structure components in an application.
What is the use of the render() function in react-native?
The render function in React is used to render HTML to a web page (). The objective of the method is to display the provided HTML code within the specified HTML element. We can read props and states in the render() method and deliver our JSX code to the app's root component.
How Linking is used in react-native?
Linking allows you to engage with both incoming and outgoing app links from a single interface. In the example illustrated above, we have used the linking for outgoing app links.
Conclusion
In this article, we've extensively discussed Geolocation in React Native. We've discussed its methods and its parameters, along with an example.
We hope this blog has helped you enrich your knowledge regarding Geolocation in React Native. Do check out the awesome content on the Coding Ninjas Website, Android Development, Coding Ninjas Studio Interview Bundle, Coding Ninjas Studio Interview Experiences, Coding Ninjas Studio Contests, Coding Ninjas Courses, Coding Ninjas Studio Problems, and Coding Ninjas Studio Test Series. Do not forget to upvote our blog to help other ninjas grow.
Happy Coding!