【问题标题】:Know nearest pin in a MapView from current location从当前位置了解 MapView 中最近的图钉
【发布时间】:2015-08-31 11:38:00
【问题描述】:

我正在使用在城市内添加了一些图钉的 MapView。此外,当前用户位置会显示在地图中。有了这两个已知的东西(用户位置和引脚),我想在标签中显示离用户最近的引脚。

【问题讨论】:

标签: xcode swift mapkit core-location


【解决方案1】:

没有直接的 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

【讨论】:

    【解决方案2】:

    使用 distanceFromLocation 计算所有距离:

    let distance = fromLocation.distanceFromLocation(toLocation)
    

    您可以在 for 循环中计算每个引脚的距离,以便找到较慢的引脚

    看看这个: Find nearest annotations from user location ios?

    【讨论】:

      【解决方案3】:

      您可能会查看 Mapbox Distance API 之类的东西,以便在单个 REST 请求中执行此操作:https://www.mapbox.com/blog/distance-api/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-11-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多