ios - 从用户位置查找数组中最接近的经度和纬度,并根据从一个纬度到另一个纬度的最短距离对数组进行排序

标签 ios swift cllocationdistance

我有一个带有经纬度的数组,我想像dijkstra算法一样对数组进行排序(以找到从一个位置到另一个位置的最短距离)

for i in 0..<(dataArray - 1) {
    let coordinate1 = CLLocation(latitude: (dataArray[i] as AnyObject).value(forKey: "addressLatitude") as! CLLocationDegrees, longitude:  (dataArray[i] as AnyObject).value(forKey: "addressLongitude") as! CLLocationDegrees)
    let coordinate2 = CLLocation(latitude: (dataArray[i+1] as AnyObject).value(forKey: "addressLatitude") as! CLLocationDegrees, longitude:  (dataArray[i+1] as AnyObject).value(forKey: "addressLongitude") as! CLLocationDegrees)

    var distance: CLLocationDistance? = nil
    distance = coordinate1.distance(from: coordinate2)
    let kilometers = CLLocationDistance((distance ?? 0.0) / 1000.0)
    print(kilometers)
}

最佳答案

首先,最短需要相对于某个点,因此当您说最短时,我们假设您正在谈论用户的当前位置,因此在下面的代码中我将假设有一个变量 var userLocation: CLLocation

    let sorted = dataArray.sorted{ (a, b) -> Bool in
    let coordinate1 = CLLocation(latitude: a["addressLatitude"] as! CLLocationDegrees, longitude: a["addressLongitude"] as! CLLocationDegrees)
    let coordinate2 = CLLocation(latitude: b["addressLatitude"] as! CLLocationDegrees, longitude: b["addressLongitude"] as! CLLocationDegrees)
    return coordinate1.distance(self.userLocation) > coordinate2.distance(self.userLocation)
}

其中 letsorted 正在对您的 dataArray 进行排序。

关于ios - 从用户位置查找数组中最接近的经度和纬度,并根据从一个纬度到另一个纬度的最短距离对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52495320/

相关文章:

ios - 为什么我在 Objective-C 中的枚举上收到类型冲突警告?

ios - 在 SWIFT 中为 JSON 格式制作字符串(包括 TextView 中的换行符)的最佳方法是什么?

ios - 将 distanceFromLocation 转换为 Int

ios - 有谁知道适用于 iOS 的 newpipe android 项目吗?

ios - 解析数据后如何循环API调用Swift

ios - 使用 mapKit Swift 显示与用户的距离(英里/公里)

ios - 从用户位置查找数组中最近的经度和纬度 - iOS Swift

ios - 仅设计时 View 属性

ios - UINavigationBar 功能中的 UISwitch

javascript - BackboneJS View 渲染延迟,在 iPhone 4s (iOS 8) 上,2015 年