Add driving directions to your site with Bing Maps

In this article, you’ll first see how to create a simple web site. You’ll then add a Bing Map, add a push pin to a specific location on your map, and then add the additional feature of allowing customers to search for driving directions to your location. If you have a site already, you can skip the first section!

Microsoft WebMatrix is a free tool that allows you to create, customize and publish websites. It’s amazingly easy to use, and can be downloaded from www.microsoft.com/web/webmatrix. We’ll be using this tool as we go along in this tutorial.

Creating a webpage with WebMatrix

WebMatrix gives you a number of different ways that you can create a new website. You can use an existing open source application such as WordPress, Joomla, DotNetNuke, or Umbraco. Or, you can create a site yourself by either coding everything or using a small, simple template.

Open WebMatrix once it is downloaded and installed. On the WebMatrix Welcome Screen you will see the different options you have for creating a new application. A great place to start is the Bakery template for this example. This template is a full-featured HTML5 site that provides a basic ecommerce presence, which sounds ideal for adding a Bing map.

image

Select ‘Templates’ on the WebMatrix welcome screen

On the Template screen, select the Bakery template, give the site the name ‘Bing-Map’, and press OK

image

We will be taken to our WebMatrix workspace.

image

WebMatrix will create a bakery site for you. Press the ‘Run’ button on the menu ribbon to see it in action.

image

You can take a look around the bakery site to see everything that WebMatrix has given you. In other articles on this site you’ll explore how to customize the site and see how to, for example, turn it into a bookstore, and how to use Paypal and Facebook on it. But for now, we’ll focus on adding a Bing Map with driving directions.

Adding a Bing Map to the bakery site

In WebMatrix, go to the bakery site you created. One of the really nice things about WebMatrix is how it allows you to create site layout pages, which contain information that will appear on every page. This is where you will add your JavaScript that will load our Bing Map.

Within WebMatrix open the Files workspace. This will allow you to view the files in your bakery application. You’ll see the button to do this on the lower left hand side of the screen.

image

Select the _SiteLayout.cshtml page and open it. This page is the layout page for the whole site. You’ll see <div> tags for the <header>, and <footer>. WebMatrix ships with helpers that make site layout like this super easy. We’re going to add the Bing Map JavaScript to the header of the page, so somewhere below <head> and above </head>, add:

<script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.2">
</script>
<script type="text/javascript">
    var map = null;
    function GetMap() {            
        map = new VEMap('myMap');            
        map.LoadMap();
    }                      
</script>

This simple JavaScript function creates a new Bing Map for us to display somewhere on our site.

Next, we need to call the function in our webpage. We will want to have our Bing Map loaded when the page loads. To do this, we need to call the GetMap() function when the page loads. To do this, in _SiteLayout.cshtml find and replace <body> with <body onload="GetMap()">

This tells the page call our function that loads our Bing Map when the page loads.

The only thing left to do to add our Bing map is to define where we want to map to appear on our site. It would make sense if our Bing map appeared on our “About Us” page. Open the About.cshtml file. Directly below the </p> but before </div> add:

<h5>We are located in Downtown Seattle by the Seattle Space Needle</h5>
<div id='myMap' style="position:relative; width:600px; height:400px;"></div>
<br />

Run the file. Make sure your About.cshtml is selected on the left.

image

One problem can be noticed right away. We are just showing a generic map of the United States. It we are trying to show the location of our business, shouldn’t we have that specific location displayed when the map loads? Displaying a specific location on our map is simple and easy to do!

Firstly, get the latitude and longitude coordinates of the location you want to display on your map. (Using a Bing search for the location coordinates of the Seattle Space Needle returned the coordinates for this example) Once you have your coordinates, go back to our _SiteLayout.cshtml file. This is where we have the function that loads the map. In the GetMap() function, change

map.LoadMap();

with:

map.LoadMap(new VELatLong(47.62054, -122.34947), 16, VEMapStyle.Road, false);

Here we have defined our latitude and longitude coordinates to be the Seattle Space Needle. This means that these coordinates are the center of the map. Therefore, if we were to call the map’s GetCenter() method, we would be returned the same coordinates.

In addition to that, 3 other parameters have been defined: zoom, style, and showswitch.

  • Zoom: the zoom level to display. The valid range is between 1 and 19. The default is 4.
  • Style: specifies the map style, such as road, aerial, etc. The default is Road.
  • ShowSwitch: specifies whether to show the map mode switch on the dashboard. Default is true. (Note: if the showswitch value is set to true, the user cannot move or arrange the location viewpoint of the map)

Run the file again. Make sure the About.cshtml file is selected on the left.

image

Now our map has a specific location at the center of the map but it still does not really show where our business is located. What if we added a pushpin to signify our location?

Adding a pushpin to your Bing Map

Bing Maps have the ability to add pushpins, signifying specific locations on the map. Adding a pushpin is quite simple and requires few steps.

In our _SiteLayout.cshtml add, locate your GetMap() function. After

map.LoadMap(new VELatLong(47.62054, -122.34947), 16, VEMapStyle.Road,false);

but before }, add:

var pinpoint = map.GetCenter();          
shape = new VEShape(VEShapeType.Pushpin, pinpoint);
shape.SetTitle("Fourth Coffee Company");
shape.SetDescription("This is where we are located!");
map.AddShape(shape);

Here we get the location where we want the pushpin to be placed by using the map’s GetCenter() method. If we wanted to add a pushpin to a location that was not the center of the map, we merely have to specify new LatLong coordinates like so:

var shape = new VEShape(VEShapeType.Pushpin, (new VELatLong(39.73, -105));

After creating a pushpin, you can add information to it by using the SetTitle and SetDescription methods. Then, AddShape(shape) adds the pushpin to the map we have created.

Run the About.cshtml file.

image

We now have a pushpin noting the location of our bakery. Moving our mouse over the pushpin will cause a pop up box to appear with the title and description that we set earlier.

image

The VEShape class offers many more options for adding information to a map like adding polygons, polylines, custom pushpins, custom icons and many more. For more information on the VEShape class visit msdn.microsoft.com.

Getting Driving Directions from your Bing Map

Unfortunately, adding the option of getting driving directions from your map is slightly more complicated than adding a pushpin but you will learn how to do it, step-by-step.

The first thing we need to do is add a text box where users can type in their starting locations in order to get directions to your location. Go to the About.cshtml file. Directly below our map, add:

<form name="form" action="" method="post">
    <input id="from" type="text" value="" name="From" />
    <input id="findit" type="button" value="Find It!" name="find" onclick="GetDirections();"/>
    <br />
    <br />
    Your directions are:<br />
    <textarea id="directions" cols="50" rows="20" value=""></textarea>
</form>

The textarea is blank right now. This is where we will output the directions that we get from calling our GetDirections() functions. If we run our file, nothing will happen when we click on our button. Why? Because we have not specified what the button is supposed to do yet.

Now that we have told our button to GetDirections() when it is clicked, we need to write that function. Same with before, go to our _SiteLayout.cshtml file. Directly under our GetMap() function, add our GetDirections() function, like so:

function GetDirections() {
    var what = document.getElementById('from').value;
    var options = new VERouteOptions();
    options.DrawRoute      = true;
    options.SetBestMapView = false;
    options.RouteCallback  = onGotRoute;
    map.GetDirections([what, map.GetCenter()], options);   
}

One thing to notice is that our options variable is calling a method called onGotRoute but we haven’t written that function yet. We will do that now.

We will add our onGotRoute function directly after our GetDirections() function. In the _SiteLayout.cshtml file, directly after } closing the GetDirections() function, add:

function onGotRoute(route) {
    var legs = route.RouteLegs;
    var turns = "Total distance: " + route.Distance.toFixed(1) + " mi\n";
    var numTurns = 0;
    var leg = null;
    for (var i = 0; i < legs.length; i++) {
        leg = legs[i];
        var turn = null;  
        for (var j = 0; j < leg.Itinerary.Items.length; j ++) {
            turn = leg.Itinerary.Items[j];
            numTurns++;
            turns += numTurns + ".\t" + turn.Text + " (" + turn.Distance.toFixed(1) + " mi)\n";
        }
    }
    document.getElementById("directions").value = turns;
}

You don’t really need to understand everything that our onGotRoute() function is doing. It simply processes the array of driving directions is outputs them into the textarea we created earlier.

Run our About.cshtml file. Type a starting location into the text box and hit the button. Returned on the page are the route highlighted on the map and the step by step instructions printed in our textarea.

image

You can see a version of the bakery with the Bing Map here.

You can discuss this article using the adjacent Facebook talkback.

For technical questions please visit our discussion forums, where we have a vibrant community of developers like you, as well as Microsoft engineers who are ready to answer your questions!