I have an Array with lat long and I want to sort array like dijkstra algorithm (to find the shortest distance from one to another location)
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)
}
First of all shortest needs to be relative to a certain point, so when you say shortest let's assume that you are talking about the user's current location so in the following code I'll describe assuming that there's a variable
var userLocation: CLLocation
where
let sorted
is having your dataArray sorted.