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:
Imbru's answer looks really good, but it is not very helpful if you are working with units.
Here's what I did to calculate the speed in meters per second (m/s).
object : LocationListener() {
var previousLocation: Location? = null
override fun onLocationChanged(location: Location) {
val speed = if (location.hasSpeed()) {
location.speed
} else {
previousLocation?.let { lastLocation ->
// Convert milliseconds to seconds
val elapsedTimeInSeconds = (location.time - lastLocation.time) / 1_000.
val distanceInMeters = lastLocation.distanceTo(location)
// Speed in m/s
distanceInMeters / elapsedTimeInSeconds
} ?: 0.0
}
previousLocation = location
/* There you have it, a speed value in m/s */
functionThatUsesSpeedInMeterPerSecond(speed)
. . .
}
. . .
}