CLLocation Manager returning wrong speed when tested in moving real device

Greetings,

I am implementing an app and it has a label that shows user current speed when driving in a car. I did everything to setup location manager and I have made it sure user has provided all the necessary permissions.

Apart from that I have set desiredAccuracy as kCLLocationAccuracyBestForNavigation.

Now the problem is when am travelling in a car with a much higher speed for example 50 km/hr it shows me the speed is 14 km/hr

I have used below code in didUpdateLocations

Multiline

        var speed: CLLocationSpeed = CLLocationSpeed()

        speed = locationManager.location?.speed ?? 0 * 3.6  

                if speed > 0{

            let speedTxt = String(format: "%.0f km/h", speed)

            print(speedTxt)

            kmBtn.setTitle("(speedTxt)", for: .normal)

        }else{

            kmBtn.setTitle("0 Km/h", for: .normal)

        }

BlockQuote

NOTE : Here I have multiplied the speed with 3.6 to convert the value from meterPerSecond to KilometerPerHour

Why its not returning the accurate speed and how to get that ?

Replies

You may want to use the CLLocation passed to didUpdateLocations() for more stable results. Accessing locationManager.location is not an atomic read of an instance variable, but it results in a quite expensive interprocess lookup.

Also, you have not stated the .activityType you have set. CoreLocation may return adjusted CLLocation values based on the activity type, and this could be throwing off your calculations. If you are driving a car, you would want to use the .automotiveNavigation activity type.

Another step you may want to take is to check the horizontal accuracy of the location, and make sure it is not a low accuracy reading due to environmental issues.

Of course, you will also want to make sure that your app is authorized for precise location.