为什么我不能显示两个位置之间的蓝线?迅速

时间:2019-03-16 04:01:45

标签: dictionary mapkit

我是新手。我试图通过一条蓝线连接两个位置,但该线从未出现。引脚位置显示一张地图。 导入UIKit 导入MapKit

customPin类:NSObject,MKAnnotation {     var座标:CLLocationCoordinate2D     var标题:字符串?     var字幕:字符串?

init( pinTitle:String, pinSubTitle:String, location:CLLocationCoordinate2D){
    self.title = pinTitle
    self.subtitle = pinSubTitle
    self.coordinate = location
}

} ViewController类:UIViewController,MKMapViewDelegate {

@IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {

    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    let sourceLocation = CLLocationCoordinate2D(latitude: 39.173209, longitude: -73.9772)
    let destinationLocation = CLLocationCoordinate2D(latitude: 40.7527, longitude: -90.177429)
    let sourcePin = customPin(pinTitle: "Kansas City", pinSubTitle: "", location: sourceLocation)
    let destinationPin = customPin(pinTitle: "St. Louis", pinSubTitle: "", location: destinationLocation)
    self.mapView.addAnnotation(sourcePin)
    self.mapView.addAnnotation(destinationPin)

    let sourcePlaceMark = MKPlacemark(coordinate: sourceLocation)
    let destinationPlaceMark = MKPlacemark(coordinate: destinationLocation)

    let directionRequest = MKDirectionsRequest()

    directionRequest.source = MKMapItem(placemark: sourcePlaceMark)
    directionRequest.destination = MKMapItem(placemark: destinationPlaceMark)
    directionRequest.transportType = .automobile


    let directions = MKDirections(request: directionRequest)
    directions.calculate{(response, error) in
        guard let directionResonse = response else{
            if let error = error {
                print("we have error getting directions ==\(error.localizedDescription)")
            }
            return
        }
        let route = directionResonse.routes[0]
        self.mapView.add(route.polyline, level: .aboveRoads)

        let rect = route.polyline.boundingMapRect
        self.mapView.setRegion(MKCoordinateRegionForMapRect(rect), animated: true)
    }
    self.mapView.delegate = self
}
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
    let renderer = MKPolylineRenderer(overlay: overlay)
    renderer.strokeColor = UIColor.blue
    renderer.lineWidth = 4.0
    return renderer
}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

0 个答案:

没有答案