我正试图从用户当前位置获取最近的引脚
- 我的代码是
let locationManager = CLLocationManager()
var currentCoordinate: CLLocationCoordinate2D!
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let pins = mapView?.annotations
// let currentLocation = mapView?.userLocation.location
guard let currentLocation = locations.first else { return }
currentCoordinate = currentLocation.coordinate
let nearestPin: MKAnnotation? = pins!.reduce((CLLocationDistanceMax,nil)) { (nearest, pin) -> (CLLocationDistance, MKAnnotation) in
let coord = pin.coordinate
let loc = CLLocation(latitude: coord.latitude, longitude: coord.longitude)
let distance = currentLocation.distance(from: loc)
print(distance, pin)
return distance < nearest.0 ? (distance, pin) : nearest as! (CLLocationDistance, MKAnnotation)
} as AnyObject as? MKAnnotation
if nearestPin?.title == "Test"{
print("found")
}
}
但它不能正常工作
谢谢
首先,检查您是否在Info.plist
中设置了位置隐私。在您的情况下,我检查扩展中的授权。
CLLocationManagerDelegate
extension ViewController: CLLocationManagerDelegate{
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
checkLocationAuthorization()
}
不要忘记在viewDidLoad()
中设置委托
代表
locationManager.delegate = self
现在谈谈实际的问题。我创建了一个可以调用的私有函数
locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
搜索最近的注释
我想你已经宣布了一系列注释(var annotation = [MKAnnotation]()
)。我们将使用这些注释(在我的情况下是巴黎和阿姆斯特丹)与我们当前的位置相比,找到最接近的。
private func getNearestPin(locations: [CLLocation]) -> MKAnnotation? {
let allPinsOnMap = mapView?.annotations
guard let currentLocation = locations.first else { return nil }
if let pins = allPinsOnMap {
let nearestPin: (CLLocationDistance, MKAnnotation?) = pins.reduce((CLLocationDistanceMax,nil))
{ (nearest, pin) -> (CLLocationDistance, MKAnnotation?) in
let coord = pin.coordinate
let loc = CLLocation(latitude: coord.latitude, longitude: coord.longitude)
let distance = currentLocation.distance(from: loc)
return distance < nearest.0 ? (distance, pin) : nearest
}
return nearestPin.1
}
return nil
}
该函数将返回一个MKAnnotation?
,所以当我们调用该函数时,我们必须检查它是否不返回nil。我们在扩展中调用此函数!
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let nearest = getNearestPin(locations: locations) {
if nearest.title == "Amsterdam" {
print("Nearest is available: \(nearest.title! ?? "Title")")
}
}
}
如果您有任何其他问题或反馈,请告诉我们!