如何在 mapkit 中获取到最近引脚的方向

how to get direction to nearest pin in mapkit

我正在尝试获取从用户当前位置到最近的图钉的方向

-我的密码是

 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
}


该函数将 return 一个 MKAnnotation? 所以当我们调用该函数时,我们必须检查它是否 return 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")")
        }
    }
}

如果您有任何进一步的问题或反馈,请告诉我!