Search code examples
iosswiftgpsgeolocation

Keeping the max speed in a speedometer app


I'm doing a simple speedometer to learn Swift and Geolocation, and I'm stuck with the maximum speed. I want to display the maximum speed achieved by the user, but instead my label displays the current speed. Here is the code for the function:

func locationManager(manager:CLLocationManager, didUpdateLocations locations:[CLLocation]) {
        var latestLocation = locations.last as CLLocation!
        var maxSpeed: Double = 0

        latLabel.text = "\(latestLocation.coordinate.latitude)"
        lonLabel.text = "\(latestLocation.coordinate.longitude)"

        var speed: CLLocationSpeed = CLLocationSpeed()
        speed = locationManager.location!.speed
        if(speed<0){
            speed=0;
        }
        speedLabel.text = String(format: "%.0f km/h", speed * 3.6)

        maxSpeed = max(maxSpeed, speed)

        maxSpeedLabel.text = String(format: "%.0f km/h", maxSpeed*3.6)
    }

What I would like is that the speedLabel displays the current speed, and the maxSpeedLabel changes only if the current speed is higher. If I'm not clear, here is what is it doing now:

(Speed - Max Speed)

3 - 3

4 - 4

5 - 5

4 - 4

Here is what I want to achieve:

(Speed - Max Speed)

3 - 3

4 - 4

5 - 5

4 - 5

6 - 6

3 - 6

I have no idea why my code isn't working, am I missing something?

Thanks for your help!


Solution

  • you have to init the max speed out of the "func locationManager" because max speed it's inited to 0 on every "iteration" (location change) :) so max speed will be always smaller than speed