Wrong initial user location in MapView gps

80 Views Asked by At

I want to get the user location, that's what I did: I set locationManager in my ViewController:

var locationManager = CLLocationManager()

func setUpLocationManager() {
    locationManager.delegate = self
    locationManager.distanceFilter = 5
    locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
    mapView?.showsUserLocation = true
    locationManager.startUpdatingLocation()
}

Here is the function that is called once the location is updated:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if !locations.isEmpty {
            print("\(locations[0])")
        }
    }
}

It prints the initial location of the user position (see image), but I consider it wrong, because it an approximation. I also tried with:

func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) {
    let accuracy = userLocation.location?.horizontalAccuracy
    if accuracy == locationManager.desiredAccuracy {
        print("\(locations[0])")
    }
}

But it never prints the location because locationManager.desiredAccuracy is equal to -2 and accuracy is always > 0.

This what I see on the mapView:

enter image description here enter image description here

Initially the user pin shows a position near to the real position (but it is not right), subsequently the user pin moves to the real user position. I want the function didUpdateLocations to be called when the user pin is on the right position. My question is similar to this, but it was in objective-c.

Any hints? Thanks

1

There are 1 best solutions below

1
On BEST ANSWER

ref. MKMapView's user location is wrong on startup or resume

Swift version:

func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) {
    let accuracy = userLocation.location?.horizontalAccuracy
    if accuracy ... {

    }
}