Saturday, 20 April 2013

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


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



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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
protected void Page_Load(object sender, EventArgs e)
{
GetLocations();
}
 
private void GetLocations()
{
     string ConString =
     @"Data Source=DEEPAK\SQLSERVER2005;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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
</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 callscreateDrivingRoute function.
In createDrivingRoute function, a DirectionsManager object is created if it is null using createDirectionsManagerfunction. createDirectionsManagerfunction creates DirectionsManager usingMicrosoft.Maps.Directions.DirectionsManagerclass which takes a map object as parameter.
Then two Waypoints are created usingMicrosoft.Maps.Directions.Waypoint class with Latitudes and Longitudes retrieved from ddlFrom and ddlTo DropDownLists. These Waypoints are then added to the DirectionsManager object usingaddWaypoint method. Before that direction’s route mode is set usingsetRequestOptions method of the DirectionsManager class. DirectionsManger’s routeMode is set toMicrosoft.Maps.Directions.RouteMode.drivingfor 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

No comments:

Post a Comment