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

By | February 25, 2013

Download Source Code


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

Get Direction using Bing Map


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

[sourcecode language=”html”]
<body onload="getMap();">
<form id="form1" runat="server">

Get driving route on Bing map

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

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

<div id="status"
Click on GetDirection button

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


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

[sourcecode language=”csharp”]
protected void Page_Load(object sender, EventArgs e)

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();
if (ds.Tables.Count > 0)
ddlFrom.DataSource = ds.Tables[0].DefaultView;
ddlFrom.DataTextField = "City";
ddlFrom.DataValueField = "Location";

ddlTo.DataSource = ds;
ddlTo.DataTextField = "City";
ddlTo.DataValueField = "Location";

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

[sourcecode language=”javascript”]
<script type="text/javascript" src="">

<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

// 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) });

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

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

// Calculate route using calculateDirections method

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

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.


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

  1. ratan pandey

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

  2. ratan pandey

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

      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….

  3. ratan pandey

    Sir i want our own image as marker.
    how i can set our any image in place of balooon.
    kindly inform me ASAP

  4. ratan pandey

    आप को गणतंत्र दिवस की हार्दिक शुभकामनाये
    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


        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!

  5. Pingback: bing maps v7 modules - Search Yours

  6. Ys

    how can I add list from a sql database and see all the stops thanks


Leave a Reply

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