在 Mapkit 中绘制折线的问题

Problems drawing poly Line in Map Kit

大家下午好,

我在我的应用程序中绘制折线时遇到问题,我已经尝试在 func 方法中调用它 locationManager (_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {}

但没有生成任何东西,就像我希望标记折线的每一步,而不是在我的旅程结束时。我在下面留下我的代码:

 import UIKit
import MapKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate,MKMapViewDelegate {


@IBOutlet var Maps: MKMapView!
var locationManager = CLLocationManager()
var coordenadas = CLLocationCoordinate2D()
var startPoint = MKDirections.Request()
var ArrayDeCoordenadas: [CLLocationCoordinate2D] = []
var tap: Int = 0

func getDirections(){

    let request = MKDirections.Request()
    request.source = MKMapItem.forCurrentLocation()

       request.requestsAlternateRoutes = true

       let directions = MKDirections(request: request)
    directions.calculate { (response, error) in

           if error != nil {

               print("Error \(error)")


           } else {


               //self.dispLayRout(response)
            var overlays = self.Maps.overlays
               self.Maps.removeOverlays(overlays)

               for route in response!.routes as! [MKRoute] {

                   self.Maps.addOverlay(route.polyline,
                                        level: MKOverlayLevel.aboveRoads)

                   var instructionNumber = 0
                   for next  in route.steps {
                       instructionNumber += 1
                       print(next.instructions)
                   }

               }
           }

    }
}

   func alertLocation(title: String, Message:String){

       let alert = UIAlertController(title: title, message: Message, preferredStyle: .alert)
       let actionAlert = UIAlertAction(title: "Acept", style: .default, handler: nil)
       alert.addAction(actionAlert)
       self.present(alert, animated: true,completion: nil)

   }

   func LocalizationInit(){
       let autorization = CLLocationManager.authorizationStatus()
       switch autorization{
       case .notDetermined, .restricted:
           locationManager.requestLocation()
           break;
       case .restricted, .denied:
           alertLocation(title: "We have a Error", Message: "You have your localization restricted.")
       case .authorizedAlways,.authorizedWhenInUse:

           break;
       default:
           break;
       }
   }


@IBAction func Share(_ sender: UIButton) {
    let compartir = UIActivityViewController(activityItems: ["Share baby" as Any], 
      applicationActivities: nil)
    compartir.popoverPresentationController?.sourceView = self.view
    present(compartir,animated: true,completion: nil)
}

@IBAction func recordButton(_ sender: UIButton) {

    if sender.isSelected != true {
        tap += 1
        print("tap -> :\(tap)")
        if tap == 1{
            let annotation = MKPointAnnotation()
            annotation.title = "My route"
            annotation.subtitle = "I Hoppe"
            annotation.coordinate = coordenadas
            let annotation2 = MKPointAnnotation()
            annotation2.title = "My ride"
            annotation2.subtitle = "I Hoppe"
            annotation.coordinate = locationManager.location?.coordinate as! CLLocationCoordinate2D
            self.Maps.addAnnotation(annotation)


        }else if tap == 2 {
            tap = 0
            locationManager.stopMonitoringSignificantLocationChanges()


        }
    }

}
@IBAction func mapOptions(_ sender: UISegmentedControl) {
    switch sender.selectedSegmentIndex{
    case 0:
        Maps.mapType = MKMapType.standard
        break;
    case 1:
        Maps.mapType = MKMapType.satellite
        break;
    case 2:
        Maps.mapType = MKMapType.hybrid
        break;
    default:
        break;
    }
}



override func viewDidLoad() {
    super.viewDidLoad()


    LocalizationInit()
    let polyLineMake = MKPolyline(coordinates: ArrayDeCoordenadas, count: ArrayDeCoordenadas.count)
    self.Maps.addOverlay(polyLineMake, level: .aboveRoads)
    Maps.showsUserLocation = true
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
     DispatchQueue.main.async {
           self.locationManager.startUpdatingLocation()
       }
}

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


    coordenadas = manager.location?.coordinate as! CLLocationCoordinate2D
    ArrayDeCoordenadas.append(locations.last!.coordinate)
    print("Array de coordenadas : ->  \(ArrayDeCoordenadas)")
    let region  = MKCoordinateRegion(center: locations.last!.coordinate, latitudinalMeters: 200, 
 longitudinalMeters: 200)
    self.Maps.setRegion(region, animated: false)
    let distancia = locations.distance(from: Int(manager.location!.coordinate.latitude), to: 
    Int((locations.last?.coordinate.latitude)!))
    print("distancia \(distancia)")

}


func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    if annotation is MKUserLocation{
        return nil
    }
    let pin = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "My personal pin")
    pin.pinTintColor = UIColor.green
    return pin
}

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
    if overlay is MKPolyline{
        let polyline = overlay
        let polyLineRender = MKPolylineRenderer(overlay: polyline)
        print(" se esta generando \(polyline)")
        polyLineRender.strokeColor = UIColor.red
        polyLineRender.lineWidth = 6.0
        return polyLineRender
    }
    print(" no se esta generando")
    return MKPolylineRenderer()
} }

我已经阅读了一些文档,显然我的代码没有问题,如果有人能帮助我,那将是很大的帮助!如果你有任何方法可以帮助我知道我什么时候做的以及我走了多少步,就像某人一样,因为我没有看到 CLLocation 有一个用于此类信息的选项。

问题是没有设置地图委托对象,我也做了一些更改以添加多段线覆盖。简单但有效。祝你好运。

Maps.delegate = self

代码文件:

import UIKit
import MapKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate,MKMapViewDelegate {


@IBOutlet var Maps: MKMapView!
var locationManager = CLLocationManager()
var coordenadas = CLLocationCoordinate2D()
var startPoint = MKDirections.Request()
var ArrayDeCoordenadas: [CLLocationCoordinate2D] = []
var tap: Int = 0
var journeyPolyline: MKPolyline?

func getDirections(){

    let request = MKDirections.Request()
    request.source = MKMapItem.forCurrentLocation()

    request.requestsAlternateRoutes = true

    let directions = MKDirections(request: request)
    directions.calculate { (response, error) in

        if error != nil {

            print("Error \(error)")


        } else {


            //self.dispLayRout(response)
            var overlays = self.Maps.overlays
            self.Maps.removeOverlays(overlays)

            for route in response!.routes as! [MKRoute] {

                self.Maps.addOverlay(route.polyline,
                                     level: MKOverlayLevel.aboveRoads)

                var instructionNumber = 0
                for next  in route.steps {
                    instructionNumber += 1
                    print(next.instructions)
                }

            }
        }

    }
}

func alertLocation(title: String, Message:String){

    let alert = UIAlertController(title: title, message: Message, preferredStyle: .alert)
    let actionAlert = UIAlertAction(title: "Acept", style: .default, handler: nil)
    alert.addAction(actionAlert)
    self.present(alert, animated: true,completion: nil)

}

func LocalizationInit(){
    let autorization = CLLocationManager.authorizationStatus()
    switch autorization{
    case .notDetermined, .restricted:
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()
        break;
    case .restricted, .denied:
        alertLocation(title: "We have a Error", Message: "You have your localization restricted.")
    case .authorizedAlways,.authorizedWhenInUse:
        locationManager.startUpdatingLocation()
        break;
    default:
        break;
    }
}


@IBAction func Share(_ sender: UIButton) {
    let compartir = UIActivityViewController(activityItems: ["Share baby" as Any],
                                             applicationActivities: nil)
    compartir.popoverPresentationController?.sourceView = self.view
    present(compartir,animated: true,completion: nil)
}

@IBAction func recordButton(_ sender: UIButton) {

    if sender.isSelected != true {
        tap += 1
        print("tap -> :\(tap)")
        if tap == 1{
            let annotation = MKPointAnnotation()
            annotation.title = "My route"
            annotation.subtitle = "I Hoppe"
            annotation.coordinate = coordenadas
            let annotation2 = MKPointAnnotation()
            annotation2.title = "My ride"
            annotation2.subtitle = "I Hoppe"
            annotation.coordinate = locationManager.location?.coordinate as! CLLocationCoordinate2D
            self.Maps.addAnnotation(annotation)


        }else if tap == 2 {
            tap = 0
            locationManager.stopMonitoringSignificantLocationChanges()


        }
    }

}
@IBAction func mapOptions(_ sender: UISegmentedControl) {
    switch sender.selectedSegmentIndex{
    case 0:
        Maps.mapType = MKMapType.standard
        break;
    case 1:
        Maps.mapType = MKMapType.satellite
        break;
    case 2:
        Maps.mapType = MKMapType.hybrid
        break;
    default:
        break;
    }
}



override func viewDidLoad() {
    super.viewDidLoad()


    LocalizationInit()
    //    let polyLineMake = MKPolyline(coordinates: ArrayDeCoordenadas, count: ArrayDeCoordenadas.count)
    //    self.Maps.addOverlay(polyLineMake, level: .aboveRoads)
    Maps.showsUserLocation = true
    Maps.delegate = self
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    coordenadas = locations.first!.coordinate as! CLLocationCoordinate2D
    ArrayDeCoordenadas.append(locations.last!.coordinate)
    print("Array de coordenadas : ->  \(ArrayDeCoordenadas)")
    let region  = MKCoordinateRegion(center: locations.last!.coordinate, latitudinalMeters: 200,
                                     longitudinalMeters: 200)
    self.Maps.setRegion(region, animated: false)
    let distancia = locations.distance(from: Int(manager.location!.coordinate.latitude), to:
        Int((locations.last?.coordinate.latitude)!))
    print("distancia \(distancia)")

    let polyline = MKPolyline(coordinates: ArrayDeCoordenadas, count: ArrayDeCoordenadas.count)
    Maps.addOverlay(polyline)

    //remove old polyline
    if let oldPolyline = journeyPolyline {
        Maps.removeOverlay(oldPolyline)
    }

    journeyPolyline = polyline
}


func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    if annotation is MKUserLocation{
        return nil
    }
    let pin = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "My personal pin")
    pin.pinTintColor = UIColor.green
    return pin
}


func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
    if overlay is MKPolyline{
        let polyline = overlay
        let polyLineRender = MKPolylineRenderer(overlay: polyline)
        print(" se esta generando \(polyline)")
        polyLineRender.strokeColor = UIColor.red
        polyLineRender.lineWidth = 6.0
        return polyLineRender
    }
    print(" no se esta generando")
    return MKPolylineRenderer()
}

}