Проблемы с рисованием полигональной линии в Map Kit - PullRequest
0 голосов
/ 18 июня 2020

Добрый день, сообщество,

У меня возникли проблемы с построением Poly Line в моем приложении, я уже пытался вызвать его в забавном c методе locationManager (_ manager: CLLocationManager, didUpdateLocations location: [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 есть опция для такого типа информации.

1 Ответ

0 голосов
/ 18 июня 2020

проблема не установлена. Карта делегата объекта, также я внес некоторые изменения, чтобы добавить наложение ломаной линии. Просто, но это работает. Удачи.

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

}

...