Geeking out on Virtual Earth

Never in my life have I had so much fun with Javascript.

OK, so perhaps that's a bit of an exaggeration. But I am having fun playing around with the v5 Virtual Earth map control, as well as the nifty Virtual Earth Interactive SDK, which makes it pretty easy to quickly figure out how to do a variety of tasks, with sample code and live demos for each.

One little trick I'd like to share...showing a map is pretty darn simple:

 <head>
<script src="https://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=5">
</script>
<script>
   var map = null;
   function GetMap()
   {
      map = new VEMap('myMap');
      map.LoadMap();
   } 
</script>
</head>
<body onload="GetMap();">
   <div id='myMap' style="position:relative; width:400px; height:400px;">
   </div>
</body>

To center the map on a new location, you simply call (in Javascript) map.Find, and pass in the thing and/or address you wish to find:

 function FindLoc()
{
   try
   {
      map.Find(null, txtWhere.value);
   }
   catch(e)
   {
      alert(e.message);
   }
}

Once you've centered the map, you can easily get the latitude and longitude for that point by calling map.GetCenter:

 alert('lat/long = ' + map.GetCenter());

The tricky part is that there's a perceptible delay between when you call map.Find, and when the map is actually centered on the specified search location. If you call map.GetCenter before this operation is complete, the latitude and longitude returned will be incorrect.

The solution is provided by the callback parameter of the map.Find method. Here's the full syntax of the method:

 VEMap.Find(what, where, findType, shapeLayer, startIndex, 
   numberOfResults, showResults, createResults, useDefaultDisambiguation, 
   setBestMapView, callback);

If you don't need a particular parameter, you can simply pass in null. So our previous example, adjusted to include a callback function name, would look like this:

 function FindLoc()
{
   try
   {
      map.Find(null, txtWhere.value, null, null, null, null, null, null,
         null, null, mycallbackfunction);
   }
   catch(e)
   {
      alert(e.message);
   }
}

While I have not dug deeply into the parameters for the callback function, it takes 5 of them, and in my case, I didn't use any of them...you may want to refer to the map.Find reference for more information on this:

 function mycallbackfunction(a,b,c,d,e)
{
   alert('lat/long = ' + map.GetCenter());


}

By using the callback parameter, you ensure that the call to map.Find has completed before you grab the latitude and longitude coordinates, so your data is accurate, or at least as accurate as your search result.

I'll probably be posting some more tips around my experimentation with Virtual Earth and the map control, so check back soon for more!

Technorati Tags: geocoding, javascript, virtual earth, mapping