Home » Android » android – Travel Distance between two Lat and Long

android – Travel Distance between two Lat and Long

Posted by: admin June 15, 2020 Leave a comment

Questions:

I am looking to calculate and give the distance between two sets of Lat and Long for travel on Road.

I have had a look at the Google’s Directions and Distance Matrix API. And also done a lot of other questions on SO.

But i am not able to figure out the best possible way to do it, you need to calculate the distance to around 20-25 locations at each time.

We are building a travel app that requires this information for the user on Android device from where he is.

How to&Answers:

If You are looking for driving distance NOT shortest distance then You can try to call API service with URL like:

http://maps.googleapis.com/maps/api/distancematrix/json?origins=54.406505,18.67708&destinations=54.446251,18.570993&mode=driving&language=en-EN&sensor=false

This will result in JSON like this:

{
   "destination_addresses" : [ "Powstańców Warszawy 8, Sopot, Polska" ],
   "origin_addresses" : [ "majora Henryka Sucharskiego 69, Gdańsk, Polska" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "24,7 km",
                  "value" : 24653
               },
               "duration" : {
                  "text" : "34 min",
                  "value" : 2062
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

Result distance is actual road distance between two locations.

You can find more details in The Google Distance Matrix API

Answer:

You might want to search a little more before you ask.

Anyways, use the Haversine formula

rad = function(x) {return x*Math.PI/180;}

distHaversine = function(p1, p2) {
  var R = 6371; // earth's mean radius in km
  var dLat  = rad(p2.lat() - p1.lat());
  var dLong = rad(p2.lng() - p1.lng());

  var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
          Math.cos(rad(p1.lat())) * Math.cos(rad(p2.lat())) * Math.sin(dLong/2) * Math.sin(dLong/2);
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  var dist = R * c;

  return dist.toFixed(3);
}

Answer:

It give the distance between two locations.

First you need to get latitude, longitude of source and same for destination. Pass these in this method.

It return you distance between them.

public float distanceFrom(float lat1, float lng1, float lat2, float lng2) {
    double earthRadius = 3958.75;
    double dLat = Math.toRadians(lat2-lat1);
    double dLng = Math.toRadians(lng2-lng1);
    double a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) * Math.sin(dLng/2) * Math.sin(dLng/2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    double dist = earthRadius * c;
    int meterConversion = 1609;
    return new Float(dist * meterConversion).floatValue();
}