【问题标题】:Problems drawing poly Line in Map Kit在 Mapkit 中绘制折线的问题
【发布时间】:2020-06-18 15:42:58
【问题描述】:

大家下午好,

我在应用程序中绘制折线时遇到问题,我已经尝试在 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 有此类信息的选项。

【问题讨论】:

    标签: ios iphone xcode swift4 swift5.2


    【解决方案1】:

    问题是没有设置 Map 委托对象,我也做了一些更改以添加折线覆盖。很简单,但它正在工作。祝你好运。

    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()
    }
    

    }

    【讨论】:

      猜你喜欢
      • 2017-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-18
      • 2011-02-19
      • 2018-11-13
      • 2016-04-12
      相关资源
      最近更新 更多