provide simple method to get current speed (implementing speedometer)

时间秒杀一切 提交于 2020-01-13 14:27:04

问题


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:

  1. Create a CLLocationmanager instance
  2. Assign a delegate with the appropriate callback method
  3. Check to see if the "speed" is set on the CLLocation in the callback, if it is - there's your speed
  4. (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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!