我有一个纬度为lat的数组,并且我想对数组进行排序,例如 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)
}
答案 0 :(得分: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进行排序的地方。