I need to get the speed and heading from the gps. However the only number i have from location.getSpeed()
is 0 or sometimes not available. my code:
Based on other suggestions here I put together this code with comments to why:
public static float getSpeedKmh(Location newLocation, Location previousLocation)
{
if(newLocation == null) throw new IllegalArgumentException("newLocation must not be null");
float speed = -1.0f;
if(newLocation.hasSpeed()) /* gps doppler speed at the current moment preferred */
{
speed = newLocation.getSpeed();
}else /* may be wifi or celltower based location: compute AVERAGE speed since last fix */
{
if(previousLocation == null) throw new IllegalArgumentException("Cannot compute speed without previousLocation (was null)");
if(previousLocation.getTime()==newLocation.getTime())
throw new IllegalArgumentException("Cannot compute speed from same time locations!"); /* diff by zero protection */
speed = newLocation.distanceTo(previousLocation) * 1000.0f /* time diff in millis so multiply by 1000 */
/ Math.abs(newLocation.getTime() - previousLocation.getTime()); /* Math abs: so you can even swap new and older location without effect */
}
return speed * 3.6f; /* m/s -> km/h */
}