Click here to Skip to main content
Click here to Skip to main content

Driving route path direction with Bing Maps in C#/XAML in a Windows 8 app

, 18 Apr 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
How to draw a driving route direction with Bing Maps in C#/XAML in a Windows 8 app.

Introduction  

This article guides you in drawing a path from one location to another using Bing Maps in a C#/XAML Metro app. Basically it uses Bing Maps' REST service and the helper class is used for JSON parsing.

Background

In one of my Windows 8 apps, I have to give a feature for drawing a route path direction from one location to another with Bing Maps. I searched a lot on Google and finally I found an example in JavaScript, but I wanted it in C#/XAML. So then I asked in the MSDN forums and Richard Brundritt helped me by providing the Bing Maps REST Service helper class. With that I managed to do it. Here I am posting the code. All REST links and URL Templates can be found here. Thanks to Richard Brundritt Smile | <img src=

Prerequisites 

To use Bing Maps in your Windows 8 app, you will need the Bing Map SDK and a key for using them. So here is a CodeProject article which shows the basic Bing Maps operations. And then add the Bing Maps REST Service .NET Libraries. Please note Bing map is not supported in some regions. You can check here. When it's not supported you will get red crossed circle on Bing map. So to set supported region you have to set HomeRegion  property, otherwise it will user user's region on Windows 8. 

Using the code 

This app uses Bing Map's REST service. So it first generates a thread to get an asynchronous response. The thread will get the URL of the REST service, which can have either both location's co-ordinates or landmarks as parameter, and it will return a JSON string. The DataContractJsonSerializer class is used for serializing the JSON response.

private async Task<Response> GetResponse(Uri uri)
{ 
    System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
    var response = await client.GetAsync(uri);
    using (var stream = await response.Content.ReadAsStreamAsync())
    {
        DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Response));
        return ser.ReadObject(stream) as Response;
    }
}

Now when the user launches, the user will be able to pass the parameters for finding the route. The user can pass co-ordinates or location, according to that the route is drawn on the map. I have passed a value for route between Ahmadabad to Mumbai. Here MyMap is the Map control in XAML and MyPushPin is the pin at the from location. The MapShapeLayer class is used to create a layer on the map to draw polylines or polygons.

private async void btnGiveDirections_Click(object sender, RoutedEventArgs e)
{
    try
    {
        tbError.Text = string.Empty;
        if (rdCoord.IsChecked == true)
            URL = "http://dev.virtualearth.net/REST/V1/Routes/Driving?o=json&wp.0=" + 
            txtFromCoord.Text + "&wp.1=" + txtToCoord.Text + 
            "&optmz=distance&rpo=Points&key=" + MyMap.Credentials;
        else
            URL = "http://dev.virtualearth.net/REST/V1/Routes/Driving?o=json&wp.0=" + 
            txtFromLocation.Text + "&wp.1=" + txtToLocation.Text + 
            "&optmz=distance&rpo=Points&key=" + MyMap.Credentials;
        Uri geocodeRequest = new Uri(URL);
        BingMapsRESTService.Response r = await GetResponse(geocodeRequest);

        geolocator = new Geolocator();
        MyPushPin = new Pushpin();

        FromLatitude = ((BingMapsRESTService.Route)(r.ResourceSets[0].Resources[0])).RoutePath.Line.Coordinates[0][0];
        FromLongitude = ((BingMapsRESTService.Route)(r.ResourceSets[0].Resources[0])).RoutePath.Line.Coordinates[0][1];

        location = new Location(FromLatitude, FromLongitude);
        MapLayer.SetPosition(MyPushPin, location);
        MyMap.Children.Add(MyPushPin);
        MyMap.SetView(location, 15.0f);

        MapPolyline routeLine = new MapPolyline();
        routeLine.Locations = new LocationCollection();
        routeLine.Color = Windows.UI.Colors.Blue;
        routeLine.Width = 5.0;
        // Retrieve the route points that define the shape of the route.
        int bound = ((BingMapsRESTService.Route)
          (r.ResourceSets[0].Resources[0])).RoutePath.Line.Coordinates.GetUpperBound(0);
        for (int i = 0; i < bound; i++)
        {
            routeLine.Locations.Add(new Location
            {
                Latitude = ((BingMapsRESTService.Route)
                  (r.ResourceSets[0].Resources[0])).RoutePath.Line.Coordinates[i][0],
                Longitude = ((BingMapsRESTService.Route)
                  (r.ResourceSets[0].Resources[0])).RoutePath.Line.Coordinates[i][1]
            });
        }
        MapShapeLayer shapeLayer = new MapShapeLayer();
        shapeLayer.Shapes.Add(routeLine);
        MyMap.ShapeLayers.Add(shapeLayer);
    }
    catch (Exception)
    {
        tbError.Text = "Error Occured !!! Please Try Again";
    }
}

Points of Interest

So this demo shows how a developer can leverage Bing Map's REST service for route calculation and drawing onto a map. 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Farhan Ghumra
Software Developer (Senior) Simform Solutions Pvt. Ltd.
India India
Windows Metro Store Apps Developer having 1+ year of experience
 
Follow me on: My Blog on Windows 8 | Twitter | Facebook | LinkedIn
 
Check Out My Articles & Tips on CodeProject
Follow on   Twitter   Google+

Comments and Discussions

 
GeneralMy vote of 5 PinmemberProgramm3r20-Feb-14 2:32 
Questioncan you help me ? Pinmemberzhaoweiyang18-Apr-13 20:17 
AnswerRe: can you help me ? PinmemberFarhan Ghumra18-Apr-13 21:12 
QuestionVery Informative PinmemberMember 19049703-Mar-13 5:37 
AnswerRe: Very Informative PinmemberFarhan Ghumra4-Mar-13 17:56 
GeneralMy vote of 5 PinmvpKanasz Robert19-Sep-12 4:32 
QuestionSome thoughts PinprotectorPete O'Hanlon19-Sep-12 0:55 
If you take the code dump and the screen shot away, there isn't much left of this article. I would expect to see more in the way of explanation.
 
Also, I'm not a fan of linking out to other articles in order to set things up - if I have to go to that article, then I'm probably not going to come back to yours, or if that article gets deleted or moved, then you've got a dead link which means I now don't know how to get a Bing key. So, rather than linking out to other articles, you should try to explain how to set things up yourself. That way, I have no incentive to go to other articles; you've got my interest and kept me there.

*pre-emptive celebratory nipple tassle jiggle* - Sean Ewington

"Mind bleach! Send me mind bleach!" - Nagy Vilmos

CodeStash - Online Snippet Management | My blog | MoXAML PowerToys | Mole 2010 - debugging made easier

GeneralMy vote of 5 PinmemberAndrei Straut18-Sep-12 23:33 
GeneralRe: My vote of 5 PinmemberFarhan Ghumra19-Sep-12 0:07 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.141015.1 | Last Updated 19 Apr 2013
Article Copyright 2012 by Farhan Ghumra
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid