我有一个带有经纬度的数组,我想像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/