Tuesday, November 27, 2007

How To Show a Map in Virtual Earth 6.0

Displaying a map using Virtual Earth 6.0 is a snap. In four short steps, you can have a fully functional, dynamic map on your web site!

Step 1.
First, we need to add a link to the Javascript that drives Virtual Earth. VE is a client-side application, which means it needs Javascript to run. If you have Javascript-disabled browsers in your user pool, you'll be out of luck.

Here's the link you'll need for the latest version of Virtual Earth:
<script type="text/javascript" src="http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6"></script>

Notice the ?v=6 appended to the end of the url. That indicates that you want to use version 6 of Virtual Earth.

You'll need this Javascript referenced and available on each page that you want the mapping functionality.

Step 2.
Next, you'll need to add a div to represent your map, like this:
<div id="myMap" style="z-index:100;position:relative; width:413px; height:327px; top:0px; left:0px; border-style:solid; border-width:1px; border-color:#C2C2C2;"></div>

Be sure this is inside of your form tags. You can style it anyway that you'd like. You can also call it anything that you'd like. I've called mine myMap. We'll use that ID in upcoming Javascript calls.

Step 3.
Next, we need to add a script block with a couple of short functions to initialize and set up the map. I've cryptically called these InitializeMap() and SetupMap(), as follows:

<script language="javascript" type="text/javascript">
//be sure this is outside the function block so you can reference it later.
var map = null;

function InitializeMap()
{
//pass in the ID of your div here
map = new VEMap('myMap');

//we need to give the map time to load before we use it...
setTimeout('SetupMap(); ', 1000);
}

function SetupMap()
{
try
{
map.LoadMap();
}
catch(e)
{
alert(e.message);
}
}
</script>

Step 4.
This is your last step. Here you need to get things kicked off. To do so, add a body.onLoad() method to your body element to fire off the InitializeMap() function, like this:
<body onload="InitializeMap()">

That's it! Compile your application and browse to your page. You should now have a map that allows panning and zooming. We'll discuss other things you can do with this map in later posts.

No comments: