Skip to main content

Removing poly line from Bing Maps on WP7

Showing a route line for a journey on a Bing Maps control in a WP7 app is relatively easy, especially if you use the WP7Contrib Bing Maps Wrapper service to call out to the Bing Maps RESTful API. It's not quite so easy to remove a route line from the control once displayed.

The background to this is in our WP7 app FINDaPAD (you'll need Zune installed) we have a page which shows the route to a property. We offer a driving route and a walking route - if it's walking distance! We don't display these routes together, they are mutually exclusive. When either of the icons is clicked to calculate the route we remove the existing route and display the new route once it has been calculated. The couple of screen shots below show 2 different routes between the same start & end locations depending whether you are driving or walking.


Shown below is a quick demo I knocked up to show the problem in more detail. This app displays a driving or walking app between the 2 UK cities Oxford & Cambridge. It also has a couple of buttons for Clearing the route line and what I call Resetting the route line. This is very similar to what we have in FINDaPAD.


The MapPolyline class in the Microsoft.Phone.Controls.Maps namespace use the Location property for the line drawn on top of the map. This is not a generic collection like IList or ObservableCollection it is of type LocationCollection coming from the same namespace. 


So my definition of Clearing would be clearing contents of this collection. This is done in the 'Clear Route' button click event handler:

private void HandleClearRouteButtonClick(object sender, RoutedEventArgs e)
{
    this.routeResult.Text = string.Empty;
    this.routeMapRouteLine.Locations.Clear();
}

Unfortunately this doesn't do what I'd expected, it does not remove the overlaid map polyline. As you can see from the screenshot below the text showing the number of points and total distance has been removed but the line hasn't.


To get this to work I had to do what I define as Resetting the clearing of the collection but then adding back in a single value. It doesn't have to any particular value it could be anything that is a valid geo-location - not GeoCoordinate.Unknown.

private void HandleResetRouteButtonClick(object sender, RoutedEventArgs e)
{
    this.routeResult.Text = string.Empty;
    this.routeMapRouteLine.Locations = new LocationCollection {this.routeMap.Center};
}

I literally resetting the collection and adding the centre point of the map back in as the start of the poly line, this gives the expected UI response when 'Reset Route' button is clicked:


I've observed the same behaviour when using the MVVM pattern (FINDaPAD) or a code behind as in the above demo. I've included the code below for the demo, including the XAML.

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">

            <Microsoft_Phone_Controls_Maps:Map x:Name="routeMap"
                                               Height="400"
                                               VerticalAlignment="Top"
                                               ZoomBarVisibility="Collapsed"
                                               CopyrightVisibility="Visible"
                                               ZoomLevel="8"
                                               AnimationLevel="UserInput"
                                               HorizontalContentAlignment="Stretch"
                                               VerticalContentAlignment="Stretch">

                <Microsoft_Phone_Controls_Maps:MapPolyline x:Name="routeMapRouteLine"
                                                           Stroke="Green"
                                                           StrokeThickness="6"
                                                           Opacity="0.7" />

            </Microsoft_Phone_Controls_Maps:Map>

            <Button Content="Driving Route"
                    Height="72"
                    Margin="0,463,232,0"
                    Name="drivingButton"
                    VerticalAlignment="Top"
                    Click="HandleDrivingButtonClick" />

            <Button Content="Walking Route"
                    Height="72"
                    Margin="209,463,6,0"
                    Name="walkingButton"
                    VerticalAlignment="Top"
                    Click="HandleWalkingButtonClick" />

            <TextBlock Height="30"
                       Margin="12,427,6,0"
                       Name="routeResult"
                       VerticalAlignment="Top" />

            <Button Content="Clear Route"
                    Height="72"
                    HorizontalAlignment="Left"
                    Margin="0,529,0,0"
                    Name="clearRouteButton"
                    VerticalAlignment="Top"
                    Width="224"
                    Click="HandleClearRouteButtonClick" />

            <Button Content="Reset Route"
                    Height="72"
                    HorizontalAlignment="Left"
                    Margin="209,529,0,0"
                    Name="resetRouteButton"
                    VerticalAlignment="Top"
                    Width="241"
                    Click="HandleResetRouteButtonClick" />
        </Grid>

As I said earlier I've used the Bing Maps Wrapper service from the WP7Contrib, you can find out more about calculating routes and all the other functionality by reading a couple of posts by RichGee and this by me.

public partial class MainPage : PhoneApplicationPage
{
    private const string RouteResultFormat = "Route Points: {0}, Distance: {1} {2}";
    private const string RouteFailedFormat = "Route Failed: {0}";

    private readonly IBingMapsService bingMapsService;
    private readonly IRouteSearchCriterion drivingCriterion;
    private readonly IRouteSearchCriterion walkingCriterion;

    public MainPage()
    {
        InitializeComponent();

        this.bingMapsService = new BingMapsService("Your credentials", "Your app id");

        var start = new GeoCoordinate(51.754240074033525, -1.25244140625);
        var end = new GeoCoordinate(52.19413974159756, 0.1318359375);

        var waypoints = new List<WayPoint> { new WayPoint { Point = start }, new WayPoint { Point = end } };

        this.drivingCriterion = CriterionFactory.CreateRouteSearch(waypoints, ModeOfTravel.Driving);
        this.walkingCriterion = CriterionFactory.CreateRouteSearch(waypoints, ModeOfTravel.Walking);

        this.routeMap.Center = new GeoCoordinate(51.88369680508255, -0.4140472412109375);
        this.routeMap.ZoomLevel = 8;
    }

    private void HandleDrivingButtonClick(object sender, RoutedEventArgs e)
    {
        this.routeProgressBar.IsIndeterminate = true;

        this.bingMapsService.CalculateARoute(drivingCriterion)
            .ObserveOnDispatcher()
            .Subscribe(this.UpdateRouteResult, () => { this.routeProgressBar.IsIndeterminate = false; });
    }
        
    private void HandleWalkingButtonClick(object sender, RoutedEventArgs e)
    {
        this.routeProgressBar.IsIndeterminate = true;

        this.bingMapsService.CalculateARoute(walkingCriterion)
            .ObserveOnDispatcher()
            .Subscribe(this.UpdateRouteResult, () => { this.routeProgressBar.IsIndeterminate = false; });
    }

    private void UpdateRouteResult(RouteSearchResult result)
    {
        if (result.HasError)
        {
            this.routeResult.Text = string.Format(RouteFailedFormat, result.ErrorDetails);
            return;
        }

        if (result.HasPoints)
        {
            this.routeResult.Text = string.Format(RouteResultFormat, result.Points.Count, result.TravelDistance, result.DistanceUnit);
            this.routeMapRouteLine.Locations = result.Points;
            this.routeMap.ZoomLevel = 8;
        }
    }

    private void HandleClearRouteButtonClick(object sender, RoutedEventArgs e)
    {
        this.routeResult.Text = string.Empty;
        this.routeMapRouteLine.Locations.Clear();
    }

    private void HandleResetRouteButtonClick(object sender, RoutedEventArgs e)
    {
        this.routeResult.Text = string.Empty;
        this.routeMapRouteLine.Locations = new LocationCollection {this.routeMap.Center};
    }
}

Comments

  1. This is very handy, thank you! Two minor notes - you forgot to include the fact that references were needed (WP7Contrib.Common and WP7Contrib.Services, I think) and there's no XAML for routeProgressBar.

    One major note: I can't actually get this to work. VS claims that:

    'System.IObservable' does not contain a definition for 'ObserveOnDispatcher' and no extension method 'ObserveOnDispatcher' accepting a first argument of type 'System.IObservable' could be found

    I get this in both the places that ObserveOnDispatcher is called for CalculateARoute, using both versions 7.0 and 7.1 of WP7Contrib. Odd!

    ReplyDelete
  2. The missing definition is caused by a incorrect reference in your app I believe, I've experience this before.

    I've uploaded the above test project onto sky drive, look at the project "BingMapRouteLine".

    https://skydrive.live.com/?cid=8503dda7ad75860b&id=8503DDA7AD75860B%21465

    ReplyDelete
  3. Ahah! Perfect. I was missing System.Reactive, System.Reactive.Windows.Threading and a using System.Reactive.Linq. Thank you indeed.

    ReplyDelete

Post a Comment

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