Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

provide simple method to get current speed (implementing speedometer)

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?

like image 381
Ilya Avatar asked Sep 11 '25 04:09

Ilya


1 Answers

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()
    
like image 64
Mark Bessey Avatar answered Sep 13 '25 06:09

Mark Bessey