Search code examples
androidperformancegpsdistancehaversine

Calculating speed from 2 points


I know this question has been asked a lot, but not yet to my satisfaction. I am trying to use the GPS of an Android device to calculate speed. A lot of people seem to reply by saying to simply use the getSpeed() function of the Location object. From what I understand though, getSpeed() will only work on certain devices that have a speed sensor built into the GPS receiver chip. I want my application to work regardless of this, so I am using the following haversine formula:

private double CalculateHaversineMI(double lat1, double long1, double lat2,double long2) {
    double dlong = (long2 - long1) * (Math.PI / 180.0f);
    double dlat = (lat2 - lat1) * (Math.PI / 180.0f);
    double a = Math.pow(Math.sin(dlat / 2.0), 2)
        + Math.cos(lat1 * (Math.PI / 180.0f))
        * Math.cos(lat2 * (Math.PI / 180.0f))
        * Math.pow(Math.sin(dlong / 2.0), 2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    double d = 3956 * c;

    return d;
}

Now what I'm trying to do is figure out how to calculate speed from this. Can anyone help me please?


Solution

  • What I can see is that your function returns correct path distance between 2 points on a sphere - it is d. But, this formula is needed only if you have 2 points on a sphere that are not close to each other (means central angle of their separation is not small, central angle of 1 degree corresponds to distance of 111 km approx, just to get feeling). If they are close to each other (which is the case for people moving and slow speed vehicles), then you do not need this formula. You can simply and very accurately approximate arc on the sphere with the straight line, and then calculation becomes trivial.

    • Sample GPS position at regular time periods. Calculate distance from the last position obtained. For that purpose you may use distanceTo() function from android.location.Location.
    • Calculate speed by dividing distance with time elapsed between 2 measurements.
    • Average calculated speeds for more accurate results, but ensure that you do not lose sensitivity to speed changes. So, you would need some trade-off on number of samples averaged.