I'm trying to add a routing feature to an app I'm working on. I found Craig Spitzkoff's article on how to draw lines on an MKMapView
which works pretty good. But since I don't have the coordinates of the points on the roads that doesn't help me as expected. Is there any way to determine the coordinates between to given points, say my current position and another address?

- 42,006
- 17
- 96
- 122

- 5,248
- 10
- 36
- 61
2 Answers
Basically you will need to make an HTTP request to the Google Directions API. The terms of service state that you have to display the results on a Google map, but I think because you are using an MKMapView, you will be fine:
the Directions API may only be used in conjunction with displaying results on a Google map; using Directions data without displaying a map for which directions data was requested is prohibited.
Check out the Directions Request for details on the parameters you will need to pass on the URL:
http://maps.google.com/maps/api/directions/output?parameters
The data you get back will be JSON or XML depending on what you asked for (output), so you will need to parse that to get the set of points describing the directions.

- 42,006
- 17
- 96
- 122
-
Thanks, Cannonade! That's it! – flohei Sep 07 '10 at 09:21
-
If you're still working on this app, watch out for licensing issues. I think it might be rejected by the app store under the terms of the MapKit licence. – Tommy Herbert Jul 21 '11 at 15:54
I know this is an old question, but nowadays you can also use MapKit’s MKDirections
. For example, here’s a routine to search for some searchString
and then add directions to the first hit on to your map view:
let request = MKLocalSearch.Request()
request.region = mapView.region
request.naturalLanguageQuery = searchString
let search = MKLocalSearch(request: request)
search.start { response, _ in
guard let mapItem = response?.mapItems.first else { return }
let request = MKDirections.Request()
request.source = MKMapItem.forCurrentLocation()
request.destination = mapItem
let directions = MKDirections(request: request)
directions.calculate { response, error in
guard let routes = response?.routes else { return }
let overlays = routes.map { $0.polyline }
self.mapView.addOverlays(overlays)
}
}
To make sure this is rendered on your map, you would make sure to set your map view’s delegate
property (either in IB or programmatically) and then implement mapView(_:rendererFor:)
:
extension MapViewController: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let renderer = MKPolylineRenderer(overlay: overlay)
renderer.strokeColor = .init(red: 0, green: 0, blue: 1, alpha: 0.7)
return renderer
}
}

- 415,655
- 72
- 787
- 1,044