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)
}
1

There are 1 best solutions below

0
On

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

    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)
}

where let sorted is having your dataArray sorted.