问题
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?
回答1:
The basic steps that you need to go through look something like this:
- Create a CLLocationmanager instance
- Assign a delegate with the appropriate callback method
- Check to see if the "speed" is set on the CLLocation in the callback, if it is - there's your speed
(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()
来源:https://stackoverflow.com/questions/38512443/provide-simple-method-to-get-current-speed-implementing-speedometer