在swift 3中绘制地图上的路线

时间:2017-06-04 06:29:05

标签: ios swift3 routes mapkit

我想在swift3中的两个坐标之间绘制路线。 我正在使用此代码,

import UIKit
import MapKit

class ViewController: UIViewController, MKMapViewDelegate {

    @IBOutlet weak var myMap: MKMapView!


var myRoute : MKRoute!

override func viewDidLoad() {

    super.viewDidLoad()

    let point1 = MKPointAnnotation()
    let point2 = MKPointAnnotation()

    point1.coordinate = CLLocationCoordinate2DMake(25.0305, 121.5360)
    point1.title = "Taipei"
    point1.subtitle = "Taiwan"
    myMap.addAnnotation(point1)

    point2.coordinate = CLLocationCoordinate2DMake(24.9511, 121.2358)
    point2.title = "Chungli"
    point2.subtitle = "Taiwan"
    myMap.addAnnotation(point2)
    myMap.centerCoordinate = point2.coordinate
    myMap.delegate = self

    //Span of the map

    myMap.setRegion(MKCoordinateRegionMake(point2.coordinate, MKCoordinateSpanMake(0.7,0.7)), animated: true)

    let directionsRequest = MKDirectionsRequest()

    let markTaipei = MKPlacemark(coordinate: CLLocationCoordinate2DMake(point1.coordinate.latitude, point1.coordinate.longitude), addressDictionary: nil)

    let markChungli = MKPlacemark(coordinate: CLLocationCoordinate2DMake(point2.coordinate.latitude, point2.coordinate.longitude), addressDictionary: nil)

    directionsRequest.source = MKMapItem(placemark: markChungli)
    directionsRequest.destination = MKMapItem(placemark: markTaipei)

    directionsRequest.transportType = MKDirectionsTransportType.automobile

    let directions = MKDirections(request: directionsRequest)

    directions.calculate(completionHandler: {

        response, error in

        if error == nil {

            self.myRoute = response!.routes[0] as MKRoute

            self.myMap.add(self.myRoute.polyline)

        }
    })
}

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) ->MKOverlayRenderer {

    let myLineRenderer = MKPolylineRenderer(polyline: myRoute.polyline)

    myLineRenderer.strokeColor = UIColor.red

    myLineRenderer.lineWidth = 3

    return myLineRenderer
}
}

这段代码给了我正确的答案 enter image description here

但是当我更改坐标时,它不会显示路线。 新的坐标是 point1 = 26.9124,75.7873 point2 = 26.9124,76.7873

1 个答案:

答案 0 :(得分:0)

看起来像Apple Maps尚不支持印度。 (quora.com/…)我想这是否是您应用程序的关键部分,您可能必须考虑使用Google地图

这些新坐标在印度,看起来那里没有方向。我收到一条错误消息,指出“错误域= MKErrorDomain代码= 4”方向不可用” UserInfo = {NSLocalizedDescription =方向不可用,MKErrorGEOError = -8,MKErrorGEOErrorUserInfo = {},MKErrorGEOTransitIncidentKey = <_ GEOTransitRoutingIncidentMessage:0x60800023dfions>,MxError = 0 NSLocalizedFailureReason =这些位置之间的方向不可用。}“

感谢Rob的这次回应。