Thursday, August 6, 2009

Using BING Maps in your ASP.NET Applications

I was using the Google Maps API last week on a project and realised that the who JavaScript thing was a bit of a pain to debug.  Although it works fine, it’s fast and is easy to use it still gave me pause for thought.  so looking around for an alternative I decided to give the Microsoft offing a quick once around the block.

Installation

First off you’ll need Visual Studio 2008 to be installed and to down load the Windows Live Tools for Microsoft Visual Studio which contains all the DLLs you’ll need.  It also comes with other bit and pieces, but this post only relates to the mapping element.

After saving the file to your local drive execute the WindowsLiveTools.msi.

image

Click next and follow all the onscreen prompts.

Adding a Map to your site

Microsoft have made it very easy to adding a map to your website, once the software has been installed you get a set of new tools in Visual Studio.

Open up any ASPX Page in design view and select the “Map” icon within the Virtual Earth group on your tool bar:

image

Drag this icon to your' page.

image

Next you need to select a ScriptManager from within the “Ajax Extensions” group and drag this to your page too.

Press Play to debug your application and make sure it’s working.

image

By default you open up over the North American continent which is not the best for an Irish company.  So to fix this we have to go into the page code behind.  Open up the default.aspx.cs file and add the following code:

protected void Page_Load(object sender, EventArgs e)
{
    Map1.Center.Latitude = 53.33306;
    Map1.Center.Longitude= -6.24889;
}

Press Play again and you should see the following:

image

Doing Directions

One of the key advantages to mapping is the ability to get directions from one place to another.  Microsoft have made this really, really easy by just creating a generic list of string with valid addresses.

Create two text boxes on the page with a submit button.

 image

In the code behind add the following to the on click event for the button.

using Microsoft.Live.ServerControls.VE;

protected void btnRoute_Click(object sender, EventArgs e)
    {
        RouteOptions options = new RouteOptions();
        options.SetBestMapView = true;  // will zoom into the route
        List<string> address = new List<string>();
        address.Add(tbxFrom.Text);
        address.Add(tbxTo.Text);
        Map1.GetDirections(address, options);
    }
}

Press play on the application; type the following into the fields and press the “Route” button:

From: East Point Business Park, Dublin, Ireland
To:     O’Connoll Street, Dublin, Ireland

image

Here is the result….  simple and easy…