Question

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?

Was it helpful?

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.

OTHER TIPS

That calculates the distance. Now as you may recall, speed = distance / time, so somewhere along the line you need to capture the time as well as the position.

On another note, the formula that you are using is way OTT for what you are trying to do. You would be better off making a number of approximations based on the fact that the path you are traversing is much less than the circumference of the earth. Then you could arrive at a much simpler formula.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top