Click here to Skip to main content
15,867,756 members
Articles / Programming Languages / C#

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

Rate me:
Please Sign up or sign in to vote.
4.87/5 (14 votes)
18 Apr 2013CPOL2 min read 89K   5.1K   26   10
How to draw a driving route direction with Bing Maps in C#/XAML in a Windows 8 app.

Image 1

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.

C#
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.

C#
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)


Written By
Technical Lead eInfochips (An Arrow Company)
India India
Leading a passionate team to build metadata driven generic IoT Platform using for the operating companies (OpCos) of a Fortune 500 American conglomerate manufacturer of industrial products having annual revenue over $7 billion. Willing to join product-based and SaaS companies having production workloads and serving end customers happily.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Flem100DK27-May-15 0:30
Flem100DK27-May-15 0:30 
GeneralMy vote of 5 Pin
Programm3r20-Feb-14 2:32
Programm3r20-Feb-14 2:32 
Questioncan you help me ? Pin
yang zhaowei18-Apr-13 20:17
yang zhaowei18-Apr-13 20:17 
AnswerRe: can you help me ? Pin
Farhan Ghumra18-Apr-13 21:12
professionalFarhan Ghumra18-Apr-13 21:12 
QuestionVery Informative Pin
Member 19049703-Mar-13 5:37
Member 19049703-Mar-13 5:37 
AnswerRe: Very Informative Pin
Farhan Ghumra4-Mar-13 17:56
professionalFarhan Ghumra4-Mar-13 17:56 
GeneralMy vote of 5 Pin
Kanasz Robert19-Sep-12 4:32
professionalKanasz Robert19-Sep-12 4:32 
QuestionSome thoughts Pin
Pete O'Hanlon19-Sep-12 0:55
subeditorPete O'Hanlon19-Sep-12 0:55 
GeneralMy vote of 5 Pin
Andrei Straut18-Sep-12 23:33
Andrei Straut18-Sep-12 23:33 
GeneralRe: My vote of 5 Pin
Farhan Ghumra19-Sep-12 0:07
professionalFarhan Ghumra19-Sep-12 0:07 

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

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