Finding and Mapping a Route in Windows Phone 8

This is a support post for the Inside Windows Phone show on location and mapping in Windows Phone 8 published here.

One of the really cool and powerful things in the Windows Phone mapping services is the ability to simple hand the Windows Phone APIs a list of geo coordinates and have it create walking or driving route on the fly. Because of the power of offline mapping in Windows Phone 8, this means that developers can create extremely powerful directional software that works even when the phone doesn’t have network connectivity.

The first thing we need to do is set up a map control on which to display our resulting route.


 <maps:Map x:Name="myMap" />

Then we’ll set up a list of geocoordinates representing the order of the places we want to use to establish our route and add some locations to it.

 List<GeoCoordinate> wayPoints = new List<GeoCoordinate>();
wayPoints.Add(new GeoCoordinate(47.60887, -122.34094));
wayPoints.Add(new GeoCoordinate(47.6396, -122.1300)); 

Then set up our RouteQuery object, assign an event handler so we can read the result, choose between a route for walking or driving and then assign the list of geo coordinates and we’re off!

 RouteQuery routeQuery = new RouteQuery();
routeQuery.QueryCompleted += routeQuery_QueryCompleted;
routeQuery.TravelMode = TravelMode.Walking;                    
routeQuery.Waypoints = wayPoints;

The RouteQuery will work for a little while and then return with (what is hopefully) a suitable route made of

 void routeQuery_QueryCompleted(object sender, QueryCompletedEventArgs<Route> e)
    if (null == e.Error)
        Route MyRoute = e.Result;

The result will be a Route object that gives an estimated duration for travelling the route as well as an enormous amount of detailed data about how to get from point A to point B (and then, subsequently, points C, D, and E). The instructions between each point are kept in the Legs property of the Route and each leg has every street and every turn detailed in the Maneuvers property. It’s really easy to work with.

But even better than that is the fact adding the route to your map is only 1 line of code (but I like to use 3 to make things easier):

 Route MyRoute = e.Result;
MapRoute mappedRoute = new MapRoute(MyRoute);

What I’ve done here is add the UI to represent this route to my map and then moved and scaled the map so that it is in the perfect spot for the user to start interacting with the route.