Virtual Earth - Finding a Postcode

I'm a big fan of Virtual Earth and often try and sneak it into demos as many people seem unaware of its existence or unaware of just how good it is. A common question I get is "Do I need to use lat / lon or can I plot a postcode?". Absolutely you can plot a postcode - the big advantage of having lat / lon is being able to pin point *exactly* where something is (and probably a little less overhead).

Here's an HTML page that uses the Virtual Earth map control to plot the location of the Microsoft Reading office postcode (RG6 1WG). You can just cut and paste the below into an HTML document to see it working. Note the reference to v6.1 of the map control script and the use of a callback on map.Find() to plot the pushpin.

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
  "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  
  <script type="text/javascript" 
    src="https://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.1"></script>
    
  <script type="text/javascript">
    var map = null;
    
    function GetMap() {
      map = new VEMap('myMap');
      map.LoadMap();
      FindLoc();
    }

    function FindLoc() {
      try {
        map.Find(null, 'RG6 1WG', null, null, null, null, null, null, false, true, LocFound);
      }
      catch (e) {
        alert(e.message);
      }
    }

    function LocFound() {
      var pPin = map.AddPushpin(map.GetCenter());
    }  
  </script>

</head>
<body onload="GetMap();">
  <div id='myMap' style="position: relative; width: 400px; height: 400px;">
  </div>
</body>
</html>

[UPDATE]

As Graham points out in the comments on this post, the above code will momentarily show the default map before displaying the postcode. To avoid this you have a couple of options, one is to hide the map until you're ready to display it. Here's a modified snippet of the above code that would achieve that:

     function LocFound() {
      var pPin = map.AddPushpin(map.GetCenter());
      document.getElementById('myMap').style.visibility = 'visible';
    }  
  </script>

</head>
<body onload="GetMap();">
  <div id='myMap' style="position: relative; width: 400px; height: 400px;visibility: hidden;">
  </div>
</body>

All I've done is changed 'myMap' to be hidden by default and added a line of code to the LocFound() method to make it visible when we've got the postcode location and are ready to display the map.

image

Loading the above HTML document in a browser will result in something similar to that on the left (click the image to see full size).

You might also want to take a look at the Vista Gadget I created some time ago which will take a location (including a postcode) or a route and plot it on a "flyout" Virtual Earth map. You can download it and pull the script apart to see how it works.

 

Technorati Tags: virtual earth,windows live