In this post, we will see how to calculate the distance between two locations in the React Native app. You will see basic distance calculation operation. I have used Geolib to get the distance between two lat-long. 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.
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.
1 | getDistance(start, end, accuracy = 1) |
This function takes up to 3 arguments. 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.
1 2 3 4 | 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.
1 | getPreciseDistance(start, end[, int accuracy]) |
The argument description is the same as getDistance() method above.
1 2 3 4 | 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
1 | cd ProjectName |
Now install the dependency
1 | 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
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 | /*Example to Calculate Distance Between Two Locations*/ import React, { Component } from 'react'; import { SafeAreaView, StyleSheet, View, Text, StatusBar, TouchableHighlight, } from 'react-native'; import { getDistance, getPreciseDistance } from 'geolib'; class App extends Component { _getDistance = () => { var dis = getDistance( { latitude: 20.0504188, longitude: 64.4139099 }, { latitude: 51.528308, longitude: -0.3817765 } ); alert(`Distance\n${dis} Meter\nor\n${dis / 1000} KM`); }; _getPreciseDistance = () => { var pdis = getPreciseDistance( { latitude: 20.0504188, longitude: 64.4139099 }, { latitude: 51.528308, longitude: -0.3817765 } ); alert(`Precise Distance\n${pdis} Meter\nor\n${pdis / 1000} KM`); }; render() { return ( lt;View style={{ flex: 1 }}> lt;StatusBar barStyle="dark-content" /> lt;SafeAreaView style={{ flex: 1 }}> lt;View style={styles.body}> lt;View style={{ flex: 1, flexDirection: 'column' }}> lt;Text style={styles.header}> Example to Calculate Distance Between Two Locations lt;/Text> lt;Text style={styles.textStyle}> Distance between{'\n'}India(20.0504188, 64.4139099) and UK (51.528308, -0.3817765) lt;/Text> lt;TouchableHighlight style={styles.buttonStyle} onPress={() => { this._getDistance(); }}> lt;Text>Get Distancelt;/Text> lt;/TouchableHighlight> lt;Text style={styles.textStyle}> Precise Distance between{'\n'}India(20.0504188, 64.4139099) and UK (51.528308, -0.3817765) lt;/Text> lt;TouchableHighlight style={styles.buttonStyle} onPress={() => { this._getPreciseDistance(); }}> lt;Text>Get Precise Distancelt;/Text> lt;/TouchableHighlight> lt;/View> lt;/View> lt;/SafeAreaView> lt;/View> ); } } const styles = StyleSheet.create({ body: { flex: 1, backgroundColor: 'white', padding: 20, }, textStyle: { marginTop: 30, fontSize: 16, textAlign: 'center', color: 'black', paddingVertical: 20, }, header: { fontSize: 22, fontWeight: '600', color: 'black', textAlign: 'center', 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 devicereact-native run-android
or on the iOS Simulator by runningreact-native run-ios
(macOS only).
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
But it’s not showing the accurate distance
Can you please share more details?
var dis = getDistance(
{ latitude: this.state.lat, longitude: this.state.long },
{ latitude: this.state.cordLatitude, longitude: this.state.cordLongitude }
);
alert(
Distance\n${dis} Meter\nor\n${dis / 1000} KM
);var di =getPreciseDistance(
{ latitude: this.state.lat, longitude: this.state.long },
{ latitude: this.state.cordLatitude, longitude: this.state.cordLongitude }
);
alert(
Distance\n${di} Meter\nor\n${di / 1000} KM
);}
??
I have start and end location which is current location i want to find the distance between start and end location