Draw polyline with mapkit Swift 3
I want to draw a polyline from the user's current location to the annotation point, but it doesn't look like anything:
@IBAction func myButtonGo(_ sender: Any) {
showRouteOnMap()
}
func showRouteOnMap() {
let request = MKDirectionsRequest()
request.source = MKMapItem(placemark: MKPlacemark(coordinate: CLLocationCoordinate2D.init(), addressDictionary: nil))
request.destination = MKMapItem(placemark: MKPlacemark(coordinate: (annotationCoordinatePin?.coordinate)!, addressDictionary: nil))
request.requestsAlternateRoutes = true
request.transportType = .automobile
let directions = MKDirections(request: request)
directions.calculate { [unowned self] response, error in guard let unwrappedResponse = response else { return }
if (unwrappedResponse.routes.count > 0) {
self.mapView.add(unwrappedResponse.routes[0].polyline)
self.mapView.setVisibleMapRect(unwrappedResponse.routes[0].polyline.boundingMapRect, animated: true)
}
}
}
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let renderer = MKPolylineRenderer(polyline: overlay as! MKPolyline)
renderer.strokeColor = UIColor.black
return renderer
}
I tried to run in debug mode and stopped at the breakpoint in the line:
directions.calculate { [unowned self] response, error in guard let unwrappedResponse = response else { return }
What is the reason for this error?
source to share
If it stops there, make sure you don't have a breakpoint:
A blue indicator in the left margin indicates that there is a breakpoint. If you have a breakpoint, just click on it to disable it (change it to blue) or drag and drop it to remove it.
If this is not a problem (i.e. it really is a crash), then we need to know what the crash is, what appears in the console, etc.
If it doesn't crash, but just doesn't draw the route, make sure you point delegate
in map view (either in viewDidLoad
or on the right side of IB).
However, a few other notes:
-
Your starting coordinate
CLLocationCoordinate2D()
(i.e. lat and long 0, 0, i.e. in the Pacific). It won't crash, but if you inspect an objecterror
, its localized description will say:Destinations not available
You must fix
coordinate
forsource
. -
You should be careful
unowned self
with asynchronous methods, as it is always possible that itself
might be freed by the time the directives are sent and will crash. Using is[weak self]
safer.
Thus:
let request = MKDirectionsRequest()
request.source = MKMapItem(placemark: MKPlacemark(coordinate: sourceCoordinate))
request.destination = MKMapItem(placemark: MKPlacemark(coordinate: destinationCoordinate))
request.requestsAlternateRoutes = true
request.transportType = .automobile
let directions = MKDirections(request: request)
directions.calculate { [weak self] response, error in
guard let response = response, error == nil, let route = response.routes.first else {
print(error?.localizedDescription ?? "Unknown error")
return
}
self?.mapView.add(route.polyline)
}
source to share