0

我有一个 lat long 的数组,我想像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)
}
4

1 回答 1

0

首先,最短需要相对于某个点,所以当你说最短时让我们假设你在谈论用户的当前位置,所以在下面的代码中我将描述假设有一个变量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)
}

let sorted你的 dataArray 在哪里排序。

于 2018-09-25T18:07:10.157 回答