如何在mapKit中绘制路线?

时间:2018-05-08 11:59:20

标签: swift mapkit

我有一个数组,其中包含路线的坐标,该数组显示在mapView上。我不能在路线上画一条线。

这是我的班级:

我导入所需的模块

import UIKit
import MapKit
import CoreLocation

然后这是我的班级

class MapViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {


    var locationManager = CLLocationManager()

    var location: [(Double, Double)]?
    var placeAnnotation:  [String]?
    var sourceLocation: CLLocationCoordinate2D!
    var indexPoint = 0


    @IBOutlet weak var mapView: MKMapView!

    let regionRadius: CLLocationDistance = 1000

    func centerMapOnLocation(location: CLLocation) {

        let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, regionRadius, regionRadius)
        mapView.setRegion(coordinateRegion, animated: true)
    }


    override func viewDidLoad() {
        super.viewDidLoad()

        mapView.delegate = self

        drawPlaceMark()

    }

    func drawPlaceMark() {

        for (x,y) in location! {
            sourceLocation = CLLocationCoordinate2D(latitude: x, longitude: y)

            let destinationPlacemark = MKPlacemark(coordinate: sourceLocation, addressDictionary: nil)

            let destinationMapItem = MKMapItem(placemark: destinationPlacemark)

            let sourceAnnotation = MKPointAnnotation()
            sourceAnnotation.title = placeAnnotation?[indexPoint]

            indexPoint = indexPoint + 1

            if let location = destinationPlacemark.location {
                sourceAnnotation.coordinate = location.coordinate
            }
            self.mapView.showAnnotations([sourceAnnotation,sourceAnnotation], animated: true )


            // Calculate the direction and draw line
            let directionRequest = MKDirectionsRequest()
            directionRequest.source = destinationMapItem

            directionRequest.destination = destinationMapItem
            directionRequest.transportType = .walking

            let directions = MKDirections(request: directionRequest)

            directions.calculate {
                (response, error) -> Void in

                guard let response = response else {
                    if let error = error {
                        print("Error: \(error)")
                    }
                    return
                }

                let route = response.routes[0]
                self.mapView.add((route.polyline), level: MKOverlayLevel.aboveRoads)

                let rect = route.polyline.boundingMapRect
                self.mapView.setRegion(MKCoordinateRegionForMapRect(rect), animated: true)
            }
        }
    }


}

如果有人可以提供帮助,请告诉我如何以正确的方式正确地做到这一点。

1 个答案:

答案 0 :(得分:0)

实施rendererFor方法。

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
    let renderer = MKPolylineRenderer(polyline: overlay as! MKPolyline)
    renderer.strokeColor = UIColor.red
    renderer.lineWidth = 3
    return renderer
}