I need to calculate distance as the user moves in android. I have the starting point coordinates and can get the user's current location. How should I calculate distance. I don't think I can call GoogleDistance Api as my application would be a real time application and calling this API would be extremely overhead or should calling GoogleDirectionsAPI would work fine.
Also I would like to test the distance travelled. How should I do it? Is there some way of sampling the data or do I really need to go out in the real world and actually travel and then test my application?
Edited: I want the distance travelled by the user and not the straight line distance between the points
Onroad distance If a probe vehicle traveling on a route R, at a constant speed v, takes time t, to reach point B from point A. Then the onroad distance between point A and B on route R, is (v × t) .
I hope following will help: In my app i started collecting lat longs after every 3fts (I set 3ft just for testing). I collected lat longs as follows:
Now I started calculating distance from point 1 to 2 and then 2 to 3 and then 3 to 4 and so on. After summing up I got total distance from 1 to 5. I used following functions to calculate distance:
public double GetDistanceFromLatLonInKm(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);
}
This method is calculating exact distance for me.
You can calculate the distance between two point using the following function
double distanceBetweenTwoPoint(double srcLat, double srcLng, double desLat, double desLng) {
double earthRadius = 3958.75;
double dLat = Math.toRadians(desLat - srcLat);
double dLng = Math.toRadians(desLng - srcLng);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
+ Math.cos(Math.toRadians(srcLat))
* Math.cos(Math.toRadians(desLat)) * Math.sin(dLng / 2)
* Math.sin(dLng / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double dist = earthRadius * c;
double meterConversion = 1609;
return (int) (dist * meterConversion);
}
For the second Part: To use mock or sample data you can use "Fake GPS" app from the play store, which will generate mock location in your device.
Happy Coding
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With