如何在 Apple 地图中更新路线 - Xcode Swift 5 in iOS 13.0?

How to Update a Route in Apple Maps - Xcode Swift 5 in iOS 13.0?

我在像 Uber 这样的 MapApp 中工作,但我需要更新折线叠加层。问题是我找不到任何响应更新路线的方法或事件。

这是我的代码:

import UIKit                                                 
import MapKit

class ViewController: UIViewController, MKMapViewDelegate {
    @IBOutlet weak var StopRoute: UIBarButtonItem!
    @IBOutlet var mapa: MKMapView!
    @IBOutlet weak var PlayRoute: UIBarButtonItem!
    var locationManager = CLLocationManager()
    var localization: CLLocation?
    var anotationCounter: Set<MKPointAnnotation> = Set<MKPointAnnotation>()
    var destinationMapItem: MKMapItem?
    var destinationMarker: MKPointAnnotation?
    open var destinationImage: UIImage?

    //Control
    var routeNum: Int = 0
    var onPathfinding = false

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.mapa.delegate = self

        //Autorización para jalar el mapa
        locationManager.requestWhenInUseAuthorization()

        //Mostar current location
        mapa.showsUserLocation = true
        mapa.showsScale = true

        //Update curent location
        locationManager.startUpdatingLocation()

        //Tratando Datos
        UserLocation()

        let tapPressRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTapPress(_:)))
        tapPressRecognizer.numberOfTapsRequired = 1

        mapa.addGestureRecognizer(tapPressRecognizer)

    }

    func UserLocation(){
        //trata de mantener actualizado lat y long siempre que sus valores sean != de nil
        localization = locationManager.location
        let latitude: Double? = localization?.coordinate.latitude
        let longitude: Double? = localization?.coordinate.longitude
        mapa.userLocation.title = "Tu ubicación"
        if let lat = latitude, let long = longitude{
            //inforrmación extrra
            mapa.userLocation.subtitle = "(\(lat); \(long))"
            AdjustMap(location: localization!)

        }
    }

    //Funcion que ajusta la pantalla y la centra en la ubiacacion
    func AdjustMap(location: CLLocation){
        let coordinatesRegion = MKCoordinateRegion(center: localization!.coordinate, latitudinalMeters: 1000, longitudinalMeters: 1000)

        mapa.setRegion(coordinatesRegion, animated: true)
    }

    //Encontrando el camino al punto designado y toma como parametro la cantidad de rutas que quiero
    func Pathfinding(routeNum: Int){
        //Limpia mapa y toma mis coordenadas
        self.mapa.removeOverlays(self.mapa.overlays)
        let coor = locationManager.location?.coordinate
        let start = MKMapItem(placemark: MKPlacemark(coordinate: coor!))

        //var routeArray = Array<MKDirections.Response>()

        let request = MKDirections.Request()
        request.source = start
        request.destination = destinationMapItem
        request.requestsAlternateRoutes = true
        request.transportType = .automobile


        let tracking = MKDirections(request: request)
        tracking.calculate(completionHandler: {(routes, error) in
            if let out = error{
                print("Error \(out)")
                return
            }
            else if let rutas = routes?.routes
            {
                self.mapa.addOverlay(rutas[self.routeNum].polyline, level: MKOverlayLevel.aboveRoads)
            }
        })
    }

    //Definiendo el gesto de toque corto sobre la pantalla
    @objc func handleTapPress(_ gestureRecognizer: UITapGestureRecognizer){
        if !onPathfinding
        {
            //LimpiaMarca anterior
            if destinationMarker != nil{
                mapa.removeAnnotation(destinationMarker!)
            }

            let tapLocation = gestureRecognizer.location(in: mapa)
            let coordinates = mapa.convert(tapLocation, toCoordinateFrom: mapa)

            destinationMapItem = MKMapItem(placemark: MKPlacemark(coordinate: CLLocationCoordinate2D(latitude: coordinates.latitude, longitude: coordinates.longitude)))

            destinationMarker = MKPointAnnotation()
            destinationMarker?.coordinate = coordinates
            mapa.addAnnotation(destinationMarker!)
        }
    }

    @IBAction func PlayRoute(_ sender: Any) {
        if !onPathfinding
        {
            onPathfinding = true
            Pathfinding(routeNum: routeNum)
            print(onPathfinding)
        }
    }

    @IBAction func StopRoute(_ sender: Any) {
        if onPathfinding
        {
            onPathfinding = false
            print(onPathfinding)
            self.mapa.removeOverlays(self.mapa.overlays)
        }
    }

    //Defininiendo la línea de traceo
    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        let renderer = MKPolylineRenderer(overlay: overlay)
        renderer.strokeColor = UIColor.orange
        renderer.lineWidth = 5
        return renderer
    }
}

我已经为 start/end 寻路功能定义了几个按钮,但我需要随着时间的推移更新路线。

我在 Apple 的文档和 Web 中寻找它,但找不到该信息。

我想你需要注册一个 CLLocationManagerDelegate 然后有这个功能

optional func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])

然后您可以根据需要更新路线。