【发布时间】:2015-08-31 11:38:00
【问题描述】:
我正在使用在城市内添加了一些图钉的 MapView。此外,当前用户位置会显示在地图中。有了这两个已知的东西(用户位置和引脚),我想在标签中显示离用户最近的引脚。
【问题讨论】:
-
谢谢,我找不到任何相关内容。我对Objective-C一无所知,但我会去看看。
标签: xcode swift mapkit core-location
我正在使用在城市内添加了一些图钉的 MapView。此外,当前用户位置会显示在地图中。有了这两个已知的东西(用户位置和引脚),我想在标签中显示离用户最近的引脚。
【问题讨论】:
标签: xcode swift mapkit core-location
没有直接的 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.
如果您不知道reduce 方法,请参阅the docs。
【讨论】:
使用 distanceFromLocation 计算所有距离:
let distance = fromLocation.distanceFromLocation(toLocation)
您可以在 for 循环中计算每个引脚的距离,以便找到较慢的引脚
【讨论】:
您可能会查看 Mapbox Distance API 之类的东西,以便在单个 REST 请求中执行此操作:https://www.mapbox.com/blog/distance-api/
【讨论】: