Contents
Geographical Distance
In this post, we will see how to calculate the distance between two locations in the React Native app. You will see the distance calculation operation between two lat-long using Geolib. This library is very simple and provides a number of functions to perform different geospatial operations like distance calculation, conversion of decimal coordinates to sexagesimal and vice versa, etc. Currently, it supports 2D only which means it does not support altitude/elevation for now.
How to get the distance between two locations?
From the number of functions, we are going to use two functions for the distance calculation actually both calculate the distance but one provides normal distance and the other one provides precise distance. Have a look at the two points below:
1. Normal Distance Calculation
Normal distance calculation can be done using getDistance() function which calculates the distance between two geo coordinates.
getDistance(start, end, accuracy = 1)
This function takes up to 3 arguments. The first 2 arguments are mandatory. Coordinates can be in sexagesimal(“51° 31′ N”) or decimal(51.5103) format. The third argument is accuracy (in meters). By default, the accuracy is 1 meter. If you need a more accurate result, you can set it to a lower value, e.g. to 0.01 for centimeter accuracy.
getDistance(
{ latitude: 20.0504188, longitude: 64.4139099 },
{ latitude: 51.528308, longitude: -0.3817765 }
);
2. Precise Distance Calculation
Precise distance calculation can be done using getPreciseDistance() function which calculates the distance between two geo coordinates. This method is more accurate then getDistance, especially for long distances but it is also slower. It is using the Vincenty inverse formula for ellipsoids.
getPreciseDistance(start, end[, int accuracy])
The argument description is the same as getDistance() method above.
getPreciseDistance(
{ latitude: 20.0504188, longitude: 64.4139099 },
{ latitude: 51.528308, longitude: -0.3817765 }
);
So that were the two functions which we are going to use.
In this example, we are going to make a single screen contains two buttons to show an alert when clicked. One will show the normal distance and the other one will show the precise distance 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 init to make our React Native App. Assuming that you have node installed, you can use npm to install the react-native-cli
command line utility. Open the terminal and go to the workspace and run
npm install -g react-native-cli
Run the following commands to create a new React Native project
react-native init ProjectName
If you want to start a new project with a specific React Native version, you can use the --version argument:
react-native init ProjectName --version X.XX.X
react-native init ProjectName --version react-native@next
This will make a project structure with an index file named App.js in your project directory.
Installation of Dependency
To use getDistance
and getPreciseDistance
functions we have to install geolib
dependency. To install the dependency open the terminal and jump into your project
cd ProjectName
Now install the dependency
npm install geolib --save
Code to Calculate Distance Between Two Locations
Now Open App.js in any code editor and replace the code with the following code
App.js
// Calculate Distance Between Two Locations in React Native App
// https://aboutreact.com/react-native-calculate-distance-between-two-locations/
// import React in our code
import React from 'react';
// import all the components we are going to use
import {
SafeAreaView,
StyleSheet,
View,
Text,
TouchableHighlight,
} from 'react-native';
/*
* 1. getDistance, Calculates the distance between
* two geo coordinates.
* 2. getPreciseDistance, Calculates the distance between
* two geo coordinates. This method is more accurate then
* getDistance, especially for long distances but it is
* also slower. It is using the Vincenty inverse formula
* for ellipsoids.
*/
import {getDistance, getPreciseDistance} from 'geolib';
const App = () => {
const calculateDistance = () => {
var dis = getDistance(
{latitude: 20.0504188, longitude: 64.4139099},
{latitude: 51.528308, longitude: -0.3817765},
);
alert(
`Distance\n\n${dis} Meter\nOR\n${dis / 1000} KM`
);
};
const calculatePreciseDistance = () => {
var pdis = getPreciseDistance(
{latitude: 20.0504188, longitude: 64.4139099},
{latitude: 51.528308, longitude: -0.3817765},
);
alert(
`Precise Distance\n\n${pdis} Meter\nOR\n${pdis / 1000} KM`
);
};
return (
<SafeAreaView style={{flex: 1}}>
<View style={styles.container}>
<View style={styles.container}>
<Text style={styles.header}>
Example to Calculate Distance Between Two Locations
</Text>
<Text style={styles.textStyle}>
Distance between
{'\n'}
India(20.0504188, 64.4139099)
and
UK (51.528308, -0.3817765)
</Text>
<TouchableHighlight
style={styles.buttonStyle}
onPress={calculateDistance}>
<Text>Get Distance</Text>
</TouchableHighlight>
<Text style={styles.textStyle}>
Precise Distance between
{'\n'}
India(20.0504188, 64.4139099)
and
UK (51.528308, -0.3817765)
</Text>
<TouchableHighlight
style={styles.buttonStyle}
onPress={calculatePreciseDistance}>
<Text>
Get Precise Distance
</Text>
</TouchableHighlight>
</View>
</View>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'white',
padding: 10,
justifyContent: 'center',
},
header: {
fontSize: 22,
fontWeight: '600',
color: 'black',
textAlign: 'center',
paddingVertical: 20,
},
textStyle: {
marginTop: 30,
fontSize: 16,
textAlign: 'center',
color: 'black',
paddingVertical: 20,
},
buttonStyle: {
justifyContent: 'center',
alignItems: 'center',
height: 50,
backgroundColor: '#dddddd',
margin: 10,
},
});
export default App;
To Run the React Native App
Open the terminal again and jump into your project using.
cd ProjectName
To run the project on an Android Virtual Device or on real debugging device
react-native run-android
or on the iOS Simulator by running (macOS only)
react-native run-ios
Output Screenshots
Output in Online Emulator
This is how you can calculate the distance between two locations in the React Native app. 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. 🙂
thank you
i tried for 15 km distance from maps, but this result is 13.512 km ?
Thank You, for your valuable post
Welcome. 🙂
Hi, im unable to run the command react-native run-android. is there any other way to proceed further to get the output.