diff --git a/android/app/src/main/kotlin/dev/fiatcode/tracpulse/location/DistanceFilterProcessor.kt b/android/app/src/main/kotlin/dev/fiatcode/tracpulse/location/DistanceFilterProcessor.kt index 4d201f9..6a2b277 100644 --- a/android/app/src/main/kotlin/dev/fiatcode/tracpulse/location/DistanceFilterProcessor.kt +++ b/android/app/src/main/kotlin/dev/fiatcode/tracpulse/location/DistanceFilterProcessor.kt @@ -18,6 +18,14 @@ class DistanceFilterProcessor { private var lastLongitude: Double? = null private var lastTimestamp: Long = 0 private var lastHeading: Float? = null + private var speedCalculator: SpeedCalculator? = null + + fun getCalculatedSpeed(location: Location): Float? { + if (speedCalculator == null) { + speedCalculator = SpeedCalculator() + } + return speedCalculator?.calculateSpeed(location.latitude, location.longitude, location.time) + } fun shouldAccept(location: Location, config: FilterConfig): Boolean { val now = System.currentTimeMillis() @@ -72,6 +80,46 @@ class DistanceFilterProcessor { lastLongitude = null lastTimestamp = 0 lastHeading = null + speedCalculator?.reset() + } + + class SpeedCalculator { + private var lastLat: Double = 0.0 + private var lastLon: Double = 0.0 + private var lastTime: Long = 0 + + fun calculateSpeed(lat: Double, lon: Double, time: Long): Float? { + if (lastLat == 0.0 && lastLon == 0.0 && lastTime == 0L) { + lastLat = lat + lastLon = lon + lastTime = time + return null + } + + val distance = haversineDistance(lastLat, lastLon, lat, lon) + val timeDelta = (time - lastTime) / 1000.0 + + if (timeDelta <= 0) { + lastLat = lat + lastLon = lon + lastTime = time + return null + } + + val speed = (distance / timeDelta).toFloat() + + lastLat = lat + lastLon = lon + lastTime = time + + return speed + } + + fun reset() { + lastLat = 0.0 + lastLon = 0.0 + lastTime = 0 + } } companion object {