How to get directions using Bing Maps Directions module in ASP.NET

Download Source Code

Introduction

In this post we will see how to calculate route between two places on Bing map in ASP.NET

Get Direction using Bing Map

Description

We will use Bing Maps V7 SDK to load map and calculate directions between two locations. First we will store latitude and longitude of some cities in the SQL Server database. Then we will use Bing Maps SDK to load the map and calculate direction between two places and show it on a Bing Map

Step:1 Create a table named “Locations” in SQL Server and put some sample data in it

Locations table SQL Server

Step:2 Create a new ASP .NET project and following in HTML source of the ASPX page

<body onload="getMap();">
     <form id="form1" runat="server">

          <h2>
               Get driving route on Bing map
          </h2>

          <div style="width:900px;height:550px;">
               <div style="width:500px;height:550px;float:left;">
                    <div>
                         <span style="margin-right:100px;">From</span>
                         <span>To</span>
                    </div>

                    <div>
                         <span style="margin-right:45px;">
                              <asp:DropDownList ID="ddlFrom" runat="server">
                              </asp:DropDownList>
                         </span>
                         <span>
                              <asp:DropDownList ID="ddlTo" runat="server">
                              </asp:DropDownList>
                         </span>
                         <span>
                              <input type="button" id="btnGetDirection"
                                   value="GetDirection" onclick="createDirections();" />
                         </span>
                    </div>
                    <div id="myMap"  style="position:relative;width:500px; height:500px;">
                    </div>
               </div>

               <div id="status"
                   style="width:350px;float:right;background-color:Yellow;color:Red;text-align:center;">
                   Click on GetDirection button
               </div>

               <div id="directionsItinerary"
                    style="width:350px;height:525px; float:right; overflow:scroll;">
               </div>
          </div>

     </form>
</body>

Step:3 Add following code in code behind of the ASPX page

protected void Page_Load(object sender, EventArgs e)
{
GetLocations();
}

private void GetLocations()
{
     string ConString =
     @"Data Source=DEEPAKSQLSERVER2005;User Id=sa;Password=*******;Initial Catalog=Employee;";
     string CmdString =
          "SELECT CAST(Latitude AS VARCHAR(50))+','+CAST(Longitude AS VARCHAR(50)) AS 'Location', City, Country FROM Locations";
     using (SqlConnection con = new SqlConnection(ConString))
     {
          SqlCommand cmd = new SqlCommand(CmdString, con);
          SqlDataAdapter sda = new SqlDataAdapter(cmd);
          DataSet ds = new DataSet();
          sda.Fill(ds);
          if (ds.Tables.Count > 0)
          {
               ddlFrom.DataSource = ds.Tables[0].DefaultView;
               ddlFrom.DataTextField = "City";
               ddlFrom.DataValueField = "Location";
               ddlFrom.DataBind();

               ddlTo.DataSource = ds;
               ddlTo.DataTextField = "City";
               ddlTo.DataValueField = "Location";
               ddlTo.DataBind();
          }
     }
}

This method populates locations in DropDownLists from the database

Step:3 Add following scripts in the head section of HTML source of the ASPX page

<script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0">
</script>

<script type="text/javascript">
     var map = null;
     var directionsManager;
     var directionsErrorEventObj;
     var directionsUpdatedEventObj;

     // Loads map
     function getMap() {
          map = new Microsoft.Maps.Map(document.getElementById('myMap'),
          { credentials: 'Your Bing Maps Key' });
     }

     function createDirectionsManager() {
          // Create DirectionManager
          if (!directionsManager) {
               directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);
          }

          // Displays message if error occurs
          directionsErrorEventObj = Microsoft.Maps.Events.addHandler(directionsManager, 'directionsError',
          function (arg) {
               document.getElementById('status').innerHTML = arg.message;
          });

          // Displays message when directions has loaded
          directionsUpdatedEventObj = Microsoft.Maps.Events.addHandler(directionsManager, 'directionsUpdated',
          function () {
               document.getElementById('status').innerHTML = 'Directions loaded';
          });
     }

     function createDrivingRoute() {
          if (!directionsManager) { createDirectionsManager(); }

          // Clears previous loaded directions
          directionsManager.resetDirections();

          // Gets Latitude and Longitude from 'From' DropDownList
          var from = document.getElementById("ddlFrom").options[document.getElementById("ddlFrom").selectedIndex].value;
          var fromLat = parseFloat(from.substring(0, from.indexOf(",")));
          var fromLng = parseFloat(from.substring(from.indexOf(",") + 1));

          // Gets Latitude and Longitude from 'To' DropDownList
          var to = document.getElementById("ddlTo").options[document.getElementById("ddlTo").selectedIndex].value;
          var toLat = parseFloat(to.substring(0, to.indexOf(",")));
          var toLng = parseFloat(to.substring(to.indexOf(",") + 1));

          // Sets RouteMode to driving
          directionsManager.setRequestOptions({ routeMode: Microsoft.Maps.Directions.RouteMode.driving });

          // Create Waypoint using fromLat, fromLng and add to directionsManager
          var fromWaypoint = new Microsoft.Maps.Directions.Waypoint({ location: new Microsoft.Maps.Location(fromLat, fromLng) });
          directionsManager.addWaypoint(fromWaypoint);

          // Create Waypoint using toLat, toLng and add to directionsManager
          var toWaypoint = new Microsoft.Maps.Directions.Waypoint({ location: new Microsoft.Maps.Location(toLat, toLng) });
          directionsManager.addWaypoint(toWaypoint);

          // Sets container div for displaying direction routes
          directionsManager.setRenderOptions({ itineraryContainer: document.getElementById('directionsItinerary') });
          document.getElementById('status').innerHTML = 'Calculating directions...';

          // Calculate route using calculateDirections method
          directionsManager.calculateDirections();
     }

     // Loads Directions module and calls createDrivingRoute
     function createDirections() {
          if (!directionsManager) {
               Microsoft.Maps.loadModule('Microsoft.Maps.Directions', { callback: createDrivingRoute });
          }
          else {
               createDrivingRoute();
          }
     }
</script>

Map is loaded on Body onLoad event by calling getMap Javascript function. createDirections method is called when user clicks on GetDirection button. It loads the Directions module and calls createDrivingRoute function.

In createDrivingRoute function, a DirectionsManager object is created if it is null using createDirectionsManager function. createDirectionsManager function creates DirectionsManager using Microsoft.Maps.Directions.DirectionsManager class which takes a map object as parameter.

Then two Waypoints are created using Microsoft.Maps.Directions.Waypoint class with Latitudes and Longitudes retrieved from ddlFrom and ddlTo DropDownLists. These Waypoints are then added to the DirectionsManager object using addWaypoint method. Before that direction’s route mode is set using setRequestOptions method of the DirectionsManager class. DirectionsManger’s routeMode is set to Microsoft.Maps.Directions.RouteMode.driving for showing driving direction on the map. Other values can be transit and walking. Then itineraryContainer is set to a div with id “directionsItinerary” to show step by step route guidance in that div to reach destination from the source. It also show distance and time required to reach the destination.

Finally calculateDirections method is called to calculate the route and show it in the Bing map.

References

http://msdn.microsoft.com/en-us/library/hh312813.aspx

http://www.bingmapsportal.com/isdk/ajaxv7#DirectionsModule2

14 thoughts on “How to get directions using Bing Maps Directions module in ASP.NET

  1. ratan pandey

    आप का बहुत बहुत आभार …….बहुत ही बेहतरीन कार्य किया…..

    Reply
  2. ratan pandey

    I have some problems with solving SQL query.my back end is poor..how i can be strong.
    i have problems with solving sub query.please help me and give me some ideas for sub query

    Reply
      1. ratan pandey

        i dont want complete solution.i want to solve it on my side.i want some basic examples fro learning and practices of query…
        thanks for reply….

        Reply
  3. ratan pandey

    आप को गणतंत्र दिवस की हार्दिक शुभकामनाये
    sir
    How will calculate the distance traveled by a truck in a given state during its visit and distance traveled when the truck has reached the next state
    means state wise mileage calculations
    please help me

    Reply
      1. DEEPAK SHARMA

        Hi,
        To find when a truck with a GPS device cross a state, first you have to mark region of the states on the map and then you have to check that current location of the truck falls within which of the marked states.

        Happy Republic Day to you also!

        Reply
  4. Pingback: bing maps v7 modules - Search Yours

Leave a Reply

Your email address will not be published. Required fields are marked *