Provide Routing on MapView using MKDirections and Custom Routing

Woah… long time no blogging… Busy busy busy. Quite busy lately enhancing our app, Movreak to achieve the best movie-related iPhone app yet.

So, today I delivered a sharing of introduction to iOS 7 development for Telkom Bandung Digital Valley (BDV) members and Bandung’s developers in general. The event was full house! It’s exciting to see such a great interest.

A promise I made for the event is doing a demo to access API provided by BDV-incubated startups. Since the startup I know and that provides open API is related to mapping and routing solution for public transportation in Bandung (currently), it’s best to do the map-related demo app.

One of the new feature in iOS 7 SDK is the ability to request directions from coordinate A to coordinate B, and directly draw the direction on top of MKMapView as overlay. Simply enough, to request the directions, all you have to do is:

Using that method, pass two MKMapItem as source and destination. To create MKMapItem from coordinate, here’s the code:

To represent current location, it’s even as easy as:

Then, to set how MKMapView drawing the route polyline, implement this MKMapView  delegate method:

Use your imagination there.

Custom Routing

To provide custom routing, it involves:

  1. Get directions data from the related source, either via REST API or any protocol specified by API provider.
  2. Based on returned data, construct the array of CLLocationCoordinate2D
  3. Create instance of MKPolyline or the new MKGeodesicPolyline in iOS 7. Based on Apple doc, The MKGeodesicPolyline class represents a line shape that traces the shortest path along the surface of the Earth. As with regular polyline overlays, you specify a geodesic polyline using a set of end-to-end points where the first and last points are not connected to each other. When displayed on a two-dimensional map view, the line segment between any two points may appear curved.
  4. Add the polyline as MapView overlay
  5. There’s no step 5… Oh, may be you should configure how to display the polyline by implementing this MapView delegate method:

Sample code:

Here’s the screencast of final demo app. Don’t expect too much, I only had 1 hour to code it.

Complete source code project: http://cl.ly/102s2M2H411C

You are welcome. Enjoy!

Hey, want to learn more iOS 7 development? Let’s join my company’s iOS 7 professional training. It’s indeed learning from the experienced iOS developers in the country. More info: http://dycode.co.id. Can’t wait to share with you guys.

One thought on “Provide Routing on MapView using MKDirections and Custom Routing”

Comments are closed.