Could you please give me example how to calculate current "speed", I'm working on my first simple app ala speedometer?
I figure out to use didUpdateToLocation
also I found that I need to use formula speed = distance / duration
Is it right? how to calculate duration?
The basic steps that you need to go through look something like this:
(Optionally) if the "speed" isn't set, try calculating it from the distance between the last update and the current, divided by the difference in timestamps
import CoreLocation
class locationDelegate: NSObject, CLLocationManagerDelegate {
var last:CLLocation?
override init() {
super.init()
}
func processLocation(_ current:CLLocation) {
guard last != nil else {
last = current
return
}
var speed = current.speed
if (speed > 0) {
print(speed) // or whatever
} else {
speed = last!.distance(from: current) / (current.timestamp.timeIntervalSince(last!.timestamp))
print(speed)
}
last = current
}
func locationManager(_ manager: CLLocationManager,
didUpdateLocations locations: [CLLocation]) {
for location in locations {
processLocation(location)
}
}
}
var del = locationDelegate()
var lm = CLLocationManager();
lm.delegate = del
lm.startUpdatingLocation()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With