I have these method that adds routes for MKMapView between two CLLocation
. i have both valid pickUpDistanceLocation & dropOffDistanceLocation
func addRoutesOverLayForMapView(){
var source:MKMapItem?
var destination:MKMapItem?
println("\(pickUpDistanceLocation)")
println("\(dropOffDistanceLocation)")
//i also tested with these locations
//let sourcelocation = CLLocation(latitude: 40.7141667, longitude: -74.0063889)
//let destinationLocation = CLLocation(latitude: 38.89, longitude: 77.03)
CLGeocoder().reverseGeocodeLocation(pickUpDistanceLocation, completionHandler: {(placemarks,error)-> Void in
if (error != nil) {
println("Reverse geocoder failed with error" + error.localizedDescription)
return
}
if placemarks.count > 0 {
if let placemark: MKPlacemark = placemarks![0] as? MKPlacemark {
source = MKMapItem(placemark: placemark)
println("\(source)")
}
} else {
println("Problem with the data received from geocoder")
}
})
CLGeocoder().reverseGeocodeLocation(dropOffDistanceLocation, completionHandler: {(placemarks,error)-> Void in
if (error != nil) {
println("Reverse geocoder failed with error" + error.localizedDescription)
return
}
if placemarks.count > 0 {
if let placemark: MKPlacemark = placemarks![0] as? MKPlacemark {
destination = MKMapItem(placemark: placemark)
println("\(destination)")
}
} else {
println("Problem with the data received from geocoder")
}
})
let request:MKDirectionsRequest = MKDirectionsRequest()
request.setSource(source)
request.setDestination(destination)
request.transportType = MKDirectionsTransportType.Automobile
request.requestsAlternateRoutes = false
let directions = MKDirections(request: request)
directions.calculateDirectionsWithCompletionHandler ({
(response: MKDirectionsResponse?, error: NSError?) in
if error == nil {
self.showRoute(response!)
}
})
}
This is the method that adds the route overlay in the map
func showRoute(response:MKDirectionsResponse){
for route in response.routes as! [MKRoute]{
mapView.addOverlay(route.polyline, level: MKOverlayLevel.AboveRoads)
}
}
I get this error as the response returned error: 400
On printing error it shows as
Optional("The operation couldn’t be completed. (NSURLErrorDomain error -1011.)")
For Swift 2.1 :
Actually both source and destination variables were nil.. So i got bad response from the server.If you need just try the below code
And you should implement this delegate method,dont forget to set the mapview delegate