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

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

Custom AuthorizationHandler for SignalR Hubs

How to implement IAuthorizationRequirement for SignalR in Asp.Net Core v5.0 Been battling this for a couple of days, and eventually ended up raising an issue on Asp.Net Core gitHub  to find the answer. Wanting to do some custom authorization on a SignalR Hub when the client makes a connection (Hub is created) and when an endpoint (Hub method) is called:  I was assuming I could use the same Policy for both class & method attributes, but it ain't so - not because you can't, because you need the signatures to be different. Method implementation has a resource type of HubInnovationContext: I assumed class implementation would have a resource type of HubConnectionContext - client connects etc... This isn't the case, it's infact of type DefaultHttpContext . For me I don't even need that, it can be removed completely  from the inheritence signature and override implementation. Only other thing to note, and this could be a biggy, is the ordering of the statements in th