我正在尝试从用户当前位置获取到最近的图钉的方向
-我的代码是
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")
}
}
但是效果不佳
谢谢
答案 0 :(得分:1)
首先,检查您是否在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")")
}
}
}
如果您还有其他问题或反馈,请告诉我!