I would like to calculate the real walking distance between my current location and a list of CLLocations using MKDirections.calculate. However, for some reason the return command at the end of the function does not wait for the result and tries to return the empty variable. My code looks like this:
func getDistance (location1: CLLocation, location2: CLLocation) {
let coordinates1 = location1.coordinate
let placemark1 = MKPlacemark(coordinate: coordinates1)
let sourceItem = MKMapItem(placemark: placemark1)
let coordinates2 = location2.coordinate
let placemark2 = MKPlacemark(coordinate: coordinates2)
let destinationItem = MKMapItem(placemark: placemark2)
let request = MKDirectionsRequest()
request.source = sourceItem
request.destination = destinationItem
request.requestsAlternateRoutes = true
request.transportType = .walking
var distance: Double?
let directions = MKDirections(request: request)
directions.calculate { (response, error) in
if var routeResponse = response?.routes {
routeResponse.sort(by: {$0.expectedTravelTime < $1.expectedTravelTime})
let quickestRoute: MKRoute = routeResponse[0]
distance = Double(quickestRoute.distance)
}
}
return distance //returns nil
}
And after that I would like to use the function in a code like this:
let myLocation = CLLocation(latitude: 47.0, longitude: 17.0)
let destinationArray = [CLLocation(latitude: 47.1, longitude: 17.1), CLLocation(latitude: 47.2, longitude: 17.2), CLLocation(latitude: 47.3, longitude: 17.3)]
var distanceArray: [Double] = []
for destination in destinationArray {
distanceArray.append(getDistance(location1: myLocation, location2: destination))
}
return distanceArray
I have tried closures, but they did not work because I could not find a way to return distanceArray (the same error, it did not wait for the closure to run and returned the empty array). I have also tried DispatchGroups but they had no effect (maybe I implemented them in the wrong way).
I would really appreciate your help.
Thank you.