chehthan
chehthan

Reputation: 213

Android: calculate vehicle moving distance using mobile device

Using GPS points I am calculating by holding previous and current points with location1.distanceTo(location2) by adding each time to a variable on some time diff to get traveled distance. Is it good approach to get vehicle movement distance? Is any better approach to get accurate travel distance during moving vehicle?

Upvotes: 0

Views: 808

Answers (1)

Sam
Sam

Reputation: 41

Use the following code. I hope it will help.

public double CalculationByDistance(LatLng StartP, LatLng EndP) {
    int Radius = 6371;// radius of earth in Km
    double lat1 = StartP.latitude;
    double lat2 = EndP.latitude;
    double lon1 = StartP.longitude;
    double lon2 = EndP.longitude;
    double dLat = Math.toRadians(lat2 - lat1);
    double dLon = Math.toRadians(lon2 - lon1);
    double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
            + Math.cos(Math.toRadians(lat1))
            * Math.cos(Math.toRadians(lat2)) * Math.sin(dLon / 2)
            * Math.sin(dLon / 2);
    double c = 2 * Math.asin(Math.sqrt(a));
    double valueResult = Radius * c;
    double km = valueResult / 1;
    DecimalFormat newFormat = new DecimalFormat("####");
    int kmInDec = Integer.valueOf(newFormat.format(km));
    double meter = valueResult % 1000;
    int meterInDec = Integer.valueOf(newFormat.format(meter));
    Log.i("Radius Value", "" + valueResult + "   KM  " + kmInDec
            + " Meter   " + meterInDec);

    return Radius * c;
}



float[] results = new float[1];
Location.distanceBetween(oldPosition.latitude, oldPosition.longitude,
            newPosition.latitude, newPosition.longitude, results);

Upvotes: 0

Related Questions