Skip to main content

WP7Contrib: Criterion Factory - calculating a Route

Carrying on my series about the Criterion Factory in the WP7Contrib I thought I'd show the how we do a route search. We support multiple Criterion Factory methods for creating criterion these all depend on how much information you have available.

Calculating a route using Bing Maps REST API can be tricky and confusing there are over 10 optional parameters which you could configure to get a route between 2 locations. As with other sets of method on the Criterion Factory we've attempt to reduce the complexity by providing this abstraction.

Shown below are the methods on the Criterion Factory (for route search). As you can see all of the overloaded methods are rooted to final method which validates the Waypoints parameter. These are used like all other Criterion Factory methods to make creating criterion easier for use with the Bing Maps Wrapper service.

#region CreateRouteSearch

public static IRouteSearchCriterion CreateRouteSearch(IList<WayPoint> wayPoints)
{
    return CreateRouteSearch(wayPoints, ModeOfTravel.Driving, DistanceUnit.Kilometer, null, null, null, RoutePathOutput.Points, null, TimeType.Departure, null, null);
}

public static IRouteSearchCriterion CreateRouteSearch(IList<WayPoint> wayPoints, ModeOfTravel modeOfTravel)
{
    return CreateRouteSearch(wayPoints, modeOfTravel, DistanceUnit.Kilometer, null, null, null, RoutePathOutput.Points, null, TimeType.Departure, null, null);
}

public static IRouteSearchCriterion CreateRouteSearch(IList<WayPoint> wayPoints, ModeOfTravel modeOfTravel, DistanceUnit distanceUnit, Optimize? optimize)
{
    return CreateRouteSearch(wayPoints, modeOfTravel, distanceUnit, optimize, null, null, RoutePathOutput.Points, null, TimeType.Departure, null, null);
}

public static IRouteSearchCriterion CreateRouteSearch(IList<WayPoint> wayPoints, ModeOfTravel modeOfTravel, DistanceUnit distanceUnit, Optimize? optimize, Avoid avoid, int? heading, RoutePathOutput routePathOutput, DateTime? dateTime, TimeType timeType, int? maxSolutions, string pointOfInterest)
{
    if (wayPoints == null || wayPoints.Count < 2)
        throw new ArgumentException("Minimum number of WayPoints is 2.", "wayPoints");

    var criterion = new RouteSearchCriterion
    {
        TravelMode = modeOfTravel,
        DistanceUnit = distanceUnit,
        Optimize = optimize,
        Avoid = avoid ?? new Avoid(),
        Heading = heading,
        PathOutput = routePathOutput,
        DateTime = dateTime,
        TimeType = timeType,
        MaxSolutions = maxSolutions.HasValue ? maxSolutions.GetValueOrDefault() : 1,
        PointOfInterest = pointOfInterest
    };
    criterion.WayPoints.AddRange(wayPoints);
    return criterion;
}

#endregion

These methods allow you to easily create the required criterion for the Bing Maps Wrapper service. Obviously as your requirement gets more detailed you can specify travel types, places to avoid, road types to avoid etc.

The important and probably most complex parameter is the Waypoint list. As the names suggest all this is a set of location the route must contain. I hope its obvious but this list must contain at least 2 items - the start and destination locations for the route, you can't really have a route without these!

A Waypoint is simple the notion of a place of interest. It can be either exact geo-location specified by latitude & longitude, a landmark specified by a place name and\or post code or an address. Specifying a geo-location would be the most accurate but any of them will do.

The code below shows easy it is to get a route between 2 places with the Bing Maps Wrapper service - 8 lines of code including creating the criterion. This code is from an example called 'RouteSearch' in the Spikes directory of the WP7Contrib.

private void HandleCalculateRouteClick(object sender, RoutedEventArgs e)
{
    var waypoints = new List<WayPoint>
                        {
                            new WayPoint {Landmark = new Landmark {AreaName = this.startText.Text}},
                            new WayPoint {Landmark = new Landmark {AreaName = this.finishText.Text}}
                        };

    var criterion = CriterionFactory.CreateRouteSearch(waypoints);
    
    bingMapsService.CalculateARoute(criterion)
        .ObserveOnDispatcher()
        .Subscribe(this.DisplayRoute, this.FailedRoute);
}

This event handler is used for the following UI. This is a very simple UI, allows you to enter 2 locations and click calculate. If successful it displays the high level information about the route and then inserts the complete itinerary into a list box.


The DisplayRoute method is the Rx (reactive extensions) subscriber method, this does the binding of the results to the UI and is shown below:

private void DisplayRoute(RouteSearchResult result)
{
    this.resultStatus.Text = string.Format("Response: {0} - {1}", result.StatusCode, result.StatusDescription);

    if (result.HasSucceeded)
    {
        this.resultDistance.Text = string.Format("Distance: {0} {1}", result.TravelDistance, result.DistanceUnit);
        this.resultDuration.Text = string.Format("Duration: {0} {1}", result.TravelDuration, result.DurationUnit);

        this.resultRouteLegs.Text = string.Format("Iternary Count: {0}", result.RouteLegs[0].ItineraryItems.Count);

        this.routeLegs.ItemsSource = result.RouteLegs;
    }
}

I'm not going to go any further with examples of how to use the parameters you can specify with the Criterion Factory - hopefully they should be self explanatory.

What I am going to show is a real world example of where Rich & I are using the route search. This app is currently awaiting certification and therefore we don't want to release the name at the moment, hence the big black marks across the screen shots. The app uses the route search to find a route between 2 exact geo-locations. This is then overlaid as a set of pins and route line on the Bing Maps control. What is interesting with the results is the difference in total distance for each route - both routes start and end at the same locations but the difference is mode of travel. The left screenshot is by car and the right by foot.


As you can see from the code snippet below, we use the Criterion Factory and Bing Maps Wrapper service in exactly the same manner as the demo. Except this time we are specifying the Waypoints as exact geo-locations, the mode of travel and the distance units.

private void CalculateRoute(GeoCoordinate geoCoordinate)
{
    var waypoints = new List<WayPoint>
            {
                new WayPoint {Point = geoCoordinate},
                new WayPoint {Point = this.CurrentlySelectedProperty.GeoCoordinate},
            };

    var distanceUnit = this.settings.CurrentlySelectedCountry.IsMetric ? DistanceUnit.Kilometer : DistanceUnit.Mile;
    var modeOfTravel = this.IsCarRoute ? ModeOfTravel.Driving : ModeOfTravel.Walking;

    var criterion = CriterionFactory.CreateRouteSearch(waypoints, modeOfTravel, distanceUnit, Optimize.Time);

    this.bingMapService.CalculateARoute(criterion)
        .ObserveOnDispatcher()
        .Subscribe(this.ProcessResponse,
                   exception => this.FailedBingRouteSearch(exception, geoCoordinate),
                   this.CompletedBingRouteSearch);
}

If you want to use the demo you can, it can found in the WP7Contrib Spikes in the 'BingMaps_CriterionFactory' directory. You'll have to have a Bing AppID to use the service & demo, you can register here.

Comments

Popular posts from this blog

WPF tips & tricks: Dispatcher thread performance

Not blogged for an age, and I received an email last week which provoked me back to life. It was a job spec for a WPF contract where they want help sorting out the performance of their app especially around grids and tabular data. I thought I'd shared some tips & tricks I've picked up along the way, these aren't probably going to solve any issues you might be having directly, but they might point you in the right direction when trying to find and resolve performance issues with a WPF app. First off, performance is something you shouldn't try and improve without evidence, and this means having evidence proving you've improved the performance - before & after metrics for example. Without this you're basically pissing into the wind, which can be fun from a developer point of view but bad for a project :) So, what do I mean by ' Dispatcher thread performance '? The 'dispatcher thread' or the 'UI thread' is probably the most

Showing a message box from a ViewModel in MVVM

I was doing a code review with a client last week for a WPF app using MVVM and they asked ' How can I show a message from the ViewModel? '. What follows is how I would (and have) solved the problem in the past. When I hear the words ' show a message... ' I instantly think you mean show a transient modal message box that requires the user input before continuing ' with something else ' - once the user has interacted with the message box it will disappear. The following solution only applies to this scenario. The first solution is the easiest but is very wrong from a separation perspective. It violates the ideas behind the Model-View-Controller pattern because it places View concerns inside the ViewModel - the ViewModel now knows about the type of the View and specifically it knows how to show a message box window: The second approach addresses this concern by introducing the idea of messaging\events between the ViewModel and the View. In the example below

Implementing a busy indicator using a visual overlay in MVVM

This is a technique we use at work to lock the UI whilst some long running process is happening - preventing the user clicking on stuff whilst it's retrieving or rendering data. Now we could have done this by launching a child dialog window but that feels rather out of date and clumsy, we wanted a more modern pattern similar to the way <div> overlays are done on the web. Imagine we have the following simple WPF app and when 'Click' is pressed a busy waiting overlay is shown for the duration entered into the text box. What I'm interested in here is not the actual UI element of the busy indicator but how I go about getting this to show & hide from when using MVVM. The actual UI elements are the standard Busy Indicator coming from the WPF Toolkit : The XAML behind this window is very simple, the important part is the ViewHost. As you can see the ViewHost uses a ContentPresenter element which is bound to the view model, IMainViewModel, it contains 3 child v