Fetch Distance Between 2 Locations in React Native

In this tutorial, I will explain how you can fetch distance between 2 locations in React Native using Google Directions API. Using Google Directions API we can find the by-road distance between two latitudes & longitudes. You may find another way to find distance using some mathematical expressions without using Google API. But that gives straight line distance not by-road distance. So I will suggest using the following method to find the by-road distance between the two points.

Method to Fetch Distance Between 2 Locations

fetchDistanceBetweenPoints = (lat1, lng1, lat2, lng2) => { // Pass Latitude & Longitude of both points as a parameter

    var urlToFetchDistance = 'https://maps.googleapis.com/maps/api/distancematrix/json?units=metric&origins='+lat1+','+lng1+'&destinations='+lat2+'%2C'+lng2+'&key=' + "YOUR_GOOGLE_DIRECTIONS_API_KEY";

    fetch(urlToFetchDistance)
            .then(res => {
    return res.json()
  })
  .then(res => {
            var distanceString = res.rows[0].elements[0].distance.text;

    // Do your stuff here
  })
  .catch(error => {
            console.log("Problem occurred");
  });

}

Don’t forget to replace YOUR_GOOGLE_DIRECTIONS_API_KEY String with your Key. If you don’t have an API key you can get it by following steps at this link. This is how you can find the distance between 2 locations in React Native.

For other helping solutions, don’t forget to visit our Tutorials List.

Please share this post:
Native Mobile Application Developer (Android + IOS) having experience in Java, Swift, Kotlin, Objective C, Unity, C#, C/C++, NODE JS & PHP.

Ask a Question

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

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

%d bloggers like this: