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

Posted

技术标签:

【中文标题】如何更新 Apple 地图中的路线 - iOS 13.0 中的 Xcode Swift 5?【英文标题】:How to Update a Route in Apple Maps - Xcode Swift 5 in iOS 13.0? 【发布时间】:2019-11-21 16:26:55 【问题描述】:

我在像 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
    

我已经定义了几个按钮来启动/结束寻路功能,但我需要随着时间的推移更新路线。

我在 Apple 的 Docs 和 Web 中查找它,但找不到该信息。

【问题讨论】:

【参考方案1】:

我觉得你需要注册一个 CLLocationManagerDelegate 然后才有这个功能

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

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

【讨论】:

感谢 iCyber​​Paul 的提示。重新计算路线效果惊人。我以前尝试过时间的东西,但这要好得多。非常感谢!!! 我很高兴它成功了,请您将此标记为正确答案。谢谢。

以上是关于如何更新 Apple 地图中的路线 - iOS 13.0 中的 Xcode Swift 5?的主要内容,如果未能解决你的问题,请参考以下文章

iOS6中的iOS行车路线

如何在我的应用 iOS6 中获取行车路线

使用我的 ios App iOS 9 Swift 2.2 中的路线打开 Apple Maps App

iOS 6 中的 Apple 地图方案:如何显示标注/图钉?

如何在苹果地图中的两个位置之间绘制路线。通过 openURL

如何使用我的 ios 应用程序中的路线打开苹果地图应用程序