Calculate Distance Between Two Locations in React Native App

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

/*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 device
react-native run-android
or on the iOS Simulator by running
react-native run-ios (macOS only).

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. 🙂

9 thoughts on “Calculate Distance Between Two Locations in React Native App”

  1. 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`);
    }

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.