当使用CoreLocation点击按钮时,提高准确度以获得最近的地址



我想要的是能够走在房子的车道上,并在点击按钮时获得房子的地址。

下面的代码工作得很好,只是有时我第一次点击按钮时没有得到正确的地址,我不得不点击几次按钮。

class ViewController: UIViewController, CLLocationManagerDelegate{
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
locationManager.requestWhenInUseAuthorization()
}
@IBAction func myLocation(_ sender: Any) {
locationManager.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {(placemarks, error)-> Void in
if error != nil {
print("Reverse geocoder failed with error: (error!.localizedDescription)")
return
}
if placemarks!.count > 0 {
let placemark = placemarks![0]
self.locationManager.stopUpdatingLocation()
print("Address: (placemark.name!) (placemark.locality!), (placemark.administrativeArea!) (placemark.postalCode!)")
}else{
print("No placemarks found.")
}
})
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Location manager error: (error.localizedDescription)")
}   
}

正如你所看到的,一旦发现占位符,我就停止更新位置,这里有什么可以提高准确性的方法吗。

当点击按钮时,提高准确度以获得最近地址的逻辑是什么?

编辑如何检查

每个CLLocation对象都有一个时间戳属性,将其与now进行比较(在调用地理编码器之前(

let howRecent = newLocation.timestamp.timeIntervalSinceNow
guard newLocation.horizontalAccuracy < 20 && abs(howRecent) < 10 else { continue }

首先,在调用地理代码之前,您应该按照文档的建议检查manager.location的时间戳,因为您可能会收到一个缓存的数据,该数据并不能真正反映当前位置。

其次,您可能需要考虑使用locationManager.requestLocation(),它会报告适合您的desiredAccuracy的位置,并自动停止。

最后,在发送到地理编码之前,您可以随时检查定位对象,看看是否有足够的准确性,如果没有,请重新开始。

最新更新