1

I want to create an app in which I want to show how much distance does the user has been traveled.

I have tried using float distance = locationA.distanceTo(locationB); but it just draws a simple straight line from start to end and then calculates the distance.

I want to calculate the traveled distance based on the traveled route. Is it possible to do so using any Google maps API?

Raj
  • 2,997
  • 2
  • 12
  • 30
Adarsh
  • 45
  • 8

3 Answers3

1

you just need service to continuously observer that user change it's location then you can use these function to calculate the distance.

    public double GetDistanceInKm(double lat1, double lon1, double lat2, double lon2)
{
    final int R = 6371;
    // Radius of the earth in km
    double dLat = deg2rad(lat2 - lat1);
    // deg2rad below
    double dLon = deg2rad(lon2 - lon1);
    double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    double d = R * c;
    // Distance in km
    return d;
}
private double deg2rad(double deg)
{
    return deg * (Math.PI / 180);
}
Umer Farooq
  • 168
  • 1
  • 12
0

Assuming you have a bunch of lat long points making up a route. You have to take the distance from the previous point to the next point for all points and keep a total of that. In other words you need a-lot of lat lon data in between the route or you are just going to get a straight line.

Nigel Brown
  • 440
  • 2
  • 13
  • Yeah you are right I have to collect bunch of lats and longs to create route but what if user is offline or he is out of Internet., Can I use network provide to get user location ? – Adarsh Jul 24 '18 at 15:04
  • You should be able to use the gps to get the location that is always active, unless location services is off that is. GPS uses satellite therefore it has nothing to do with connection if you want there location – Nigel Brown Jul 24 '18 at 15:05
  • So can I get user current lats and longs using GPS without internet? – Adarsh Jul 24 '18 at 15:26
  • Please tell me how ? Can you give me some code examples or any links. – Adarsh Jul 24 '18 at 16:14
  • This link seems to have what you need: https://stackoverflow.com/questions/46906017/getting-location-offline . Hope it helps you :) – Nigel Brown Jul 24 '18 at 16:17
  • Thank you very much for your time, this one will help me. Thanks again. – Adarsh Jul 24 '18 at 17:11
0

You can use google maps api to get the distance

use this link to understand how to use it.

Elshafey
  • 72
  • 1
  • 8