从当前位置了解MapView中最近的引脚

jdm*_*718 1 xcode core-location mapkit swift

我正在使用MapView,其中添加了一个城市内的一些引脚.此外,当前用户位置显示在地图中.有了这两件事(用户位置和引脚),我想在标签中显示用户所在的最近的引脚.

rin*_*aro 6

没有直接的API可以找到它.你必须遍历所有注释.

let pins = mapView.annotations as! [MKAnnotation]
let currentLocation = mapView.userLocation.location!

let nearestPin: MKAnnotation? = pins.reduce((CLLocationDistanceMax, nil)) { (nearest, pin) in
    let coord = pin.coordinate
    let loc = CLLocation(latitude: coord.latitude, longitude: coord.longitude)
    let distance = currentLocation.distanceFromLocation(loc)
    return distance < nearest.0 ? (distance, pin) : nearest
}.1

// Here, `nearestPin` is `nil` iff there is no annotations on the map.
Run Code Online (Sandbox Code Playgroud)

如果您不知道该reduce方法,请参阅文档.