多个 Swift MapKit 路由顺序

Multiple Swift MapKit routes in order

我想把不同检查站的路线加在一起。每次,路由都以随机方式排序(执行 print(step.instructions) 时)。但在执行 print(nextCheckpoint, previousCheckpoint) 之前,它们是完全有序的。因此,在创建 MKDirections 请求时似乎存在问题(不同的路线被打乱)。供您参考:最后,每条路线都已绘制并完成,只是没有按照所需的顺序进行。这是代码:

func showExamRoute(checkpoints: Array<Checkpoints>) {
// 1. Retrieve all checkpoints and add an annotation to them
// 2. Plot Poly-line to the corresponding checkpoints
let numberOfCheckpoints = checkpoints.count - 1
for index in 0...numberOfCheckpoints {
    let checkpoint = checkpoints[index]
    let checkpointLocation2D = CLLocationCoordinate2D(latitude: checkpoint.latitude, longitude: checkpoint.longitude)
    checkpointsArray.append(checkpointLocation2D)
    let annotation = CustomAnnotationPlace(title: "1", coordinate: checkpointLocation2D, info: "checkpoint")
    mapView.addAnnotation(annotation)
}
let counterTo = checkpointsArray.count
var nextCheckpoint: CLLocationCoordinate2D!
var previousCheckpoint: CLLocationCoordinate2D!

for counter in 1...counterTo {
    if counter == counterTo {
        nextCheckpoint = checkpointsArray[0]
        previousCheckpoint = checkpointsArray[counter - 1]
    } else {
        nextCheckpoint = checkpointsArray[counter]
        previousCheckpoint = checkpointsArray[counter - 1]
    }
    print(nextCheckpoint, previousCheckpoint)
    let destinationLocation = MKPlacemark(coordinate: nextCheckpoint)
    let startingLocation = MKPlacemark(coordinate: previousCheckpoint)
    let request = MKDirections.Request()
    request.source = MKMapItem(placemark: startingLocation)
    request.destination = MKMapItem(placemark: destinationLocation)
    request.transportType = .automobile
    request.requestsAlternateRoutes = false
    let directions = MKDirections(request: request)
    directions.calculate { [unowned self] (response, error) in
        guard let response = response else { return }
        let route = response.routes[0]
        self.mapView.addOverlay(route.polyline)
        self.mapView.setVisibleMapRect(route.polyline.boundingMapRect, animated: true)
        let steps = route.steps
        for i in 0...steps.count - 1 {
            let step = steps[i]
            print(step.instructions)
            examSteps.append(step)
        }
    }
}

}

感谢您的帮助!

您不能假设 directions.calculate 请求是异步的,按照 1、2、3、4、5 的顺序创建,它们都需要相同的时间来处理,因此结果将始终以 1、2、3、4、5 的顺序返回。您需要处理以任何顺序返回的结果,例如 1、3、4、5、2 - 通过将 examSteps.append(step) 替换为某些内容来实现喜欢examSteps[i] = step然后等待所有我回来