我想获取用户位置,这就是我所做的:我在 ViewController 中设置了 locationManager:
var locationManager = CLLocationManager()
func setUpLocationManager() {
locationManager.delegate = self
locationManager.distanceFilter = 5
locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
mapView?.showsUserLocation = true
locationManager.startUpdatingLocation()
}
这是位置更新后调用的函数:
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if !locations.isEmpty {
print("\(locations[0])")
}
}
}
它打印用户位置的初始位置(见图),但我认为它是错误的,因为它是一个近似值。我也尝试过:
func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) {
let accuracy = userLocation.location?.horizontalAccuracy
if accuracy == locationManager.desiredAccuracy {
print("\(locations[0])")
}
}
但它从不打印位置,因为locationManager.desiredAccuracy
等于 -2 并且accuracy
始终 > 0。
这是我在 mapView 上看到的:
最初,用户 pin 显示接近真实位置的位置(但它不正确),随后用户 pin 移动到真实用户位置。我希望在didUpdateLocations
用户引脚位于正确位置时调用该函数。我的问题与此类似,但它是在objective-c中。
有什么提示吗?谢谢