Getting Started With Via Virtual Earth | Via Virtual Earth

Virtual Earth Home.

Getting Started With Via Virtual Earth

Displaying the Default Map

Displaying the default map, which includes all of the navigation functionality, consists of the following steps:

1. At the top of the HTML page add the following DOCTYPE declaration.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

2. In the header section of an HTML page, add a META element with the charset attribute set to “utf-8”, as follows.

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 

Note: Your page must use UTF-8 encoding to draw certain elements of the map.

3. Also in the header section, add a reference to the map control, as follows.

<script type="text/javascript" 
src="http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6"></script>

4. In the body of the page, add a DIV element to the page to contain the map. The size of the map is defined by the height and width of the DIV element. The position of the map is set by using the “position”, “top”, and “left” properties. You can set these values either inline or by defining the values in a style class and then referencing that class, as follows.

<div id='myMap' style="position:absolute; width:400px; height:400px;"></div>
 

or

.map {
   position: absolute;
   top: 20;
   left: 10;
   width: 400px;
   height: 400px;
   border:#555555 2px solid;
}
...
<div id="map" class="map"></div>

Note: If you do not specify a width, a default width of 600 pixels is used. The default height is 400 pixels. For cross-browser compatibility, you should always specify the position attribute (both “absolute” and “relative” are valid values). If you use a percentage width and or height in the map DIV, it is the percentage of the parent width or height, respectively.

5. Create a new instance of the VEMap Class and call the VEMap.LoadMap Method, as follows.

var map = new VEMap('myMap');
map.LoadMap();

Note: In most cases you must call the call LoadMap method before you call a VEMap method or attempt to access a VEMap property. The exceptions, which you must call after creating the new VEMap object but before you call the LoadMap method on that object, are: VEMap.onLoadMap Property VEMap.SetDashboardSize Method

Customizing the Map When Loading

You can also specify the location, zoom level, and map style of the map when you first load it. To do this, use the overloaded VEMap.LoadMap Method function as follows to pass in the location, zoom level, map style, whether the map is locked, map mode, whether to show the map mode switch, and how much of a tile buffer to display around the map.

var map = new VEMap('myMap');
map.LoadMap(new VELatLong(47.6, -122.33, 0, VEAltitudeMode.RelativeToGround), 
10, VEMapStyle.Road, false, VEMapMode.Mode2D, true, 1);

Example

A complete Web page with all of the elements required to show a map may look like the following.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
   <head>
      <title></title>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

      <script type="text/javascript" src="/Portals/0/http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6"></script>

      <script type="text/javascript">
         var map = null;

         var LA = new VELatLong(34.0540, -118.2370);

         var pinPoint = null;
         var pinPixel = null;
                  
         function GetMap()
         {
            map = new VEMap('myMap');
            map.LoadMap(LA, 14, VEMapStyle.Road, false, VEMapMode.Mode2D, true, 1);

            AddPin();
         }

         function getInfo()
         {
            var info;

            if (map.IsBirdseyeAvailable())
            {
                var be = map.GetBirdseyeScene();

                info  = "ID: "          + be.GetID() + "\n";
                info += "thumbnail: "   + be.GetThumbnailFilename()+ "\n";
                info += "orientation: " + be.GetOrientation()+ "\n";
                info += "height: "      + be.GetHeight() + "\n";
                info += "width: "       + be.GetWidth() + "\n";

                var pixel = be.LatLongToPixel(map.GetCenter(), map.GetZoomLevel());

                info += "LatLongToPixel: " + pixel.x + ", " + pixel.y + "\n";

                // Check to see if the current birdseye view contains the pushpin pixel point.
                info += "contains pixel " + pinPixel.x + ", " + pinPixel.y + ": " + 
                        be.ContainsPixel(pinPixel.x, pinPixel.y, map.GetZoomLevel()) + "\n";
                
                // Check to see if the current view contains the pushpin LatLong.
                info += "contains latlong " + pinPoint + ": " + be.ContainsLatLong(pinPoint) + "\n";
                
                // This method may return null, depending on the selected view and map style.
                info += "latlong: " + map.PixelToLatLong(pixel);

                alert(info);
            }
            else
            {
                var center = map.GetCenter();

                info  = "Zoom level:\t" + map.GetZoomLevel() + "\n";
                info += "Latitude:\t"   + center.Latitude    + "\n";
                info += "Longitude:\t"  + center.Longitude;

                alert(info);
            }
         }
         
         function AddPin()
         {
            // Add a new pushpin to the center of the map.
            pinPoint = map.GetCenter();
            pinPixel = map.LatLongToPixel(pinPoint);
            map.AddPushpin(pinPoint);
         }
      </script>
   </head>
   <body onload="GetMap();">
      <div id='myMap' style="position:relative; width:400px; height:400px;"></div>
       <input id="btnGetInfo" type="button" value="Get Scene Information" name="getinfo" onclick="getInfo();">
       <br/>
        (zoom out 5 clicks to get latitude/longitude and zoom level)
   </body>
</html>

Controlling the Map

After you have a map on your Web page, you can programmatically change the map. You can change the map style, adjust the zoom level, pan the map to a new location, show and hide the default navigation control, and add your own controls to the map.

Changing the Map View

There are several ways you can programmatically change the map view. You can:

  • Zoom the map in or out by calling the VEMap.ZoomIn Method and VEMap.ZoomOut Method.
  • Zoom to a specific level by calling the VEMap.SetZoomLevel Method.
  • Set the center of the map by calling the VEMap.SetCenter Method, or set the center of the map and zoom in by calling the VEMap.SetCenterAndZoom Method.
  • Change the map style by calling the VEMap.SetMapStyle Method.
  • Let Virtual Earth determine the best map to show, based on your set of points, pushpins, or polylines. You accomplish this by passing an array of points or lines to the VEMap.SetMapView Method.

Showing and Hiding Controls

You can show and hide the default map navigation control by calling the VEMap.HideDashboard Method and VEMap.ShowDashboard Method. You can also create your own map navigation control in HTML, and then add the control to the map by calling the VEMap.AddControl Method.

Adding Shapes to a Map

You can use shapes for tasks such as marking locations, highlighting geographical boundaries, and displaying information on a map.

Shape Basics

There are three types of shapes: pushpins, polylines, and polygons. These correspond to a point, a line, and a polygon, respectively, on a map. With the release of Version 5, all shape objects are consolidated under the VEShape Class. You can add shapes directly to the base layer of a map, or use the VEShapeLayer Class to create shape layers, which you can then use to create and manage arbitrary groups of shapes. Once the shape objects are added, you can set and get shape properties by calling methods against each object directly.

VEMap Shape Methods

Use the VEMap.AddShape Method to add shapes to a map’s base layer. This method adds an existing VEShape object to the base layer of the map. Use the VEMap.DeleteShape Methodto delete a single shape from the base layer, and VEMap.DeleteAllShapes Method to delete all shape objects from the base layer.

VEShapeLayer Shape Methods

Use the VEShapeLayer.AddShape Method to add a shape. Use the VEShapeLayer.DeleteShape Method to delete a single shape from a layer, and VEShapeLayer.DeleteAllShapes Method method to delete all shape objects from a layer.

Setting and Getting VEShape Object Properties

Once a shape has been added to a map, use the methods of the VEShape class to set and get the shape’s properties. These properties control aspects of the shape such as line color and width, fill color and transparency, custom icon, image file, Latitude/Longitude coordinates, and more. As of Version 5, the title and description properties can contain custom HTML, which you can use to further extend and modify your shapes.

Adding a Shape to a Map

Adding a shape to a map consists of the following steps:

1. Define an array of VELatLong objects. Polygon objects require a minimum of three points, polyline objects require a minimum of two points, and pushpin objects require only one point which can be part of an array (the method uses the first VELatLong object), or a single VELatLong object.

var points = new Array(
   new VELatLong(45.01188,-111.06687, 0, VEAltitudeMode. RelativeToGround),
   new VELatLong(45.01534,-104.06324, 0, VEAltitudeMode. RelativeToGround),
   new VELatLong(41.01929,-104.06, 0, VEAltitudeMode. RelativeToGround),
   new VELatLong(41.003,-111.05878, 0, VEAltitudeMode. RelativeToGround)
);

2. Create the VEShape object. The following code creates a new polygon shape, “myPolygon”, at the specified coordinates.

var myPolygon = new VEShape(VEShapeType.Polygon, points);

3. Add the VEShape object named “myPolygon” to the map.

var myPolygon = map.AddShape(myPolygon);

4. Edit the properties of the shape. In this example we will add strings for the title and description of the shape. Although this example shows only text, these strings can also contain valid HTML.

myPolygon.SetTitle("My Polygon");
myPolygon.SetDescription("This is the description for my polygon.");

The resulting code for the entire page might look something like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html>
   <head>
      <title>Adding a Shape to a Map</title>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
      <script type="text/javascript"  src="http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6"> </script>
      <script type="text/javascript">
      var map = null;
      var points = new Array(
         new VELatLong(45.01188,-111.06687, 0, VEAltitudeMode. RelativeToGround),
         new VELatLong(45.01534,-104.06324, 0, VEAltitudeMode. RelativeToGround),
         new VELatLong(41.01929,-104.06, 0, VEAltitudeMode. RelativeToGround),
         new VELatLong(41.003,-111.05878, 0, VEAltitudeMode. RelativeToGround)
      );

      function GetMap()
      {
         map = new VEMap('myMap');
         map.LoadMap();
         var myPolygon = new VEShape(VEShapeType.Polygon, points);
         map.AddShape(myPolygon);
         myPolygon.SetTitle("My Polygon");
         myPolygon.SetDescription("This is the description for my polygon.");
      }
      </script>
   </head>
   <body onload="GetMap();">
      <div id='myMap' style="position:relative; width:400px; height:400px;"></div>
   </body>
</html>

Adding a Shape Layer to a Map

Shape layers make it possible to create and manage multiple collections of shapes within a single map. Adding a shape to a shape layer consists of the following steps.

1. Initialize a new instance of the VEShapeLayer classVEShapeLayer Class.

var myShapeLayer = new VEShapeLayer();

2. Add the shape layer to the map, using the VEMap.AddShapeLayer Method.

map.AddShapeLayer(myShapeLayer);

The shape layer is invisible on its own, so let’s add a shape object to the layer.

3. Define an array of VELatLong objects.

var points = new Array(
   new VELatLong(45.01188,-111.06687, 0, VEAltitudeMode. RelativeToGround),
   new VELatLong(45.01534,-104.06324, 0, VEAltitudeMode. RelativeToGround),
   new VELatLong(41.01929,-104.06, 0, VEAltitudeMode. RelativeToGround),
   new VELatLong(41.003,-111.05878, 0, VEAltitudeMode. RelativeToGround)
);

4. Create a VEShape object to add to the map.

var myShape = new VEShape(VEShapeType.Polygon, points);

5. Use the VEShapeLayer.AddShape method to add the shape to the shape layer.

myShapeLayer.AddShape(myShape);

The resulting code for the entire page might look something like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html>
   <head>
      <title>Adding a Shape to a Map</title>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
      <script type="text/javascript" src="http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6"></script>
      <script type="text/javascript">
      var map = null;
      var points = new Array(
         new VELatLong(45.01188,-111.06687, 0, VEAltitudeMode. RelativeToGround),
         new VELatLong(45.01534,-104.06324, 0, VEAltitudeMode. RelativeToGround),
         new VELatLong(41.01929,-104.06, 0, VEAltitudeMode. RelativeToGround),
         new VELatLong(41.003,-111.05878, 0, VEAltitudeMode. RelativeToGround)
      );

      function GetMap()
      {
         map = new VEMap('myMap');
         map.LoadMap();
         var myShapeLayer = new VEShapeLayer();
         map.AddShapeLayer(myShapeLayer);
         var myShape = new VEShape(VEShapeType.Polygon, points);
         myShapeLayer.AddShape(myShape);
      }

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

Using Routes and Directions

You can use the Virtual Earth routing and driving directions feature to show routes on your custom maps. Routes are automatically drawn on the map, and you can customize the driving directions by writing your own event handler.

Getting a Route

If you want to display a driving route from one point to another on the map, with possible interim points, call the VEMap.GetDirections Method. Any point can be specified as an address, place name, or VELatLong Class object. The following examples are both valid.

var myOptions = new VERouteOptions();
myOptions.SetBestMapView = false; // Don't change map view
myOptions.RouteCallback = myRouteHandler;  // Gets VERoute
map.GetDirections("space needle", "LA Coliseum", "area 51", myOptions);
map.GetDirections("1 Microsoft Way, 98052", new VELatLong(47.969,-122.39, 
0, VEAltitudeMode.RelativeToGround), myOptions);

The route is drawn on the map with start and end icons and waypoint icons. Each of the icons has a default enhanced preview that displays the driving directions for that step. The myRouteHandler function gets a VERoute Class object, which you can use to display the driving directions.

Showing Driving Directions

The VERoute object contains the details about the route, including the driving directions. When calling the GetDirections method, you can specify a callback function to handle the VERoute object and use the information to display driving directions. The following example shows how to display the route information in a JavaScript alert.

function myRouteHandler(route)
{
   // Unroll route and populate alert text
   var legs          = route.RouteLegs;
   var turns         = "Turn-by-Turn Directions\n";
   var leg           = null;
   var turnNum       = 0;  // The turn #
   var totalDistance = 0;  // The sum of all leg distances

   // Get intermediate legs
   for(var i = 0; i < legs.length; i++)
   {
      // Get this leg so we don't have to derefernce multiple times
      leg = legs[i];  // Leg is a VERouteLeg object

      // Unroll each intermediate leg
      var turn        = null;  // The itinerary leg
      var legDistance = null;  // The distance for this leg

      for(var j = 0; j < leg.Itinerary.Items.length; j ++)
      {
         turnNum++;
         // turn is a VERouteItineraryItem object
         turn = leg.Itinerary.Items[j];  
         turns += turnNum + ":  " + turn.Text;
         legDistance    = turn.Distance;
         totalDistance += legDistance;

         // Round distances to 1/10ths
         // Note that miles is the default
         turns += " (" + legDistance.toFixed(1) + " miles)\n";
      }
   }
   turns += "Total distance:  " + totalDistance.toFixed(1) + " miles\n";

   // Show directions
   alert(turns);
}

Changing the Defaults

By default, driving directions are calculated by finding the quickest route by estimated driving time, and distances are calculated in miles. However, you can specify the shortest route by distance and change the units to kilometers by setting the appropriate VERouteOptions Class properties, as follows.

myOptions.RouteOptimize = VERouteOptimize.MinimizeDistance;
myOptions.DistanceUnit  = VERouteDistanceUnit.Kilometer;

Working with Bird’s Eye Images

Bird’s eye images are low-angle, very high-resolution aerial images. Unlike the other map styles, bird’s eye images exist only for specific regions and do not provide continuous map coverage.

The Virtual Earth map control has built-in support for the bird’s eye image type. You do not need to add any additional code to your Web page to enable your users to see bird’s eye images. If users move the map to a region where bird’s eye images are available, the map navigation control changes automatically.

However, there may be times when you want to show a specific bird’s eye image or create your own bird’s eye navigation control. This topic explains how to programmatically use bird’s eye images.

Determining Whether Bird’s Eye Images Are Available

You can determine whether bird’s eye images are available at any point on the map by calling the VEMap.IsBirdseyeAvailable Method.

Example.
Suppose you want to let users know when the map is centered on a location that has bird’s eye images. You need to determine whether images are available at the center of the map whenever the user moves the map to a new location. To do this, attach a function to the VEMap.onchangeview Event. In the function you attach, call the IsBirdseyeAvailable method. If the IsBirdseyeAvailable method returns a value of True, notify the user. Your code may look like the following.

map = new VEMap('myMap');
map.LoadMap(new VELatLong(33.756, -84.37), 14 ,'r' ,false); 
map.AttachEvent('onchangeview', onChangeView);
//...
function onChangeView(e) 
{
   if (map.IsBirdseyeAvailable())
   {
      alert("Bird's Eye images are available at the center of the map"); 
   } 
}

Switching to Bird’s Eye View

To programmatically switch the current map view to use bird’s eye images, call the VEMap.SetMapStyle Method as follows.

map.SetMapStyle(VEMapStyle.Birdseye)

map.SetMapStyle(VEMapStyle.Birdseye)

Using the VEBirdseyeScene Object

The VEBirdseyeScene Class object provides additional functionality when you are working with bird’s eye images. By using this object, you can:

  • Determine whether a point on the globe (a VELatLong Class object) is within the currently displayed bird’s eye image by calling the VEBirdseyeScene.ContainsLatLong Method.
  • Determine the orientation of the current image by calling the VEBirdseyeScene.GetOrientation Method.
  • Display a thumbnail of the current image by calling the VEBirdseyeScene.GetThumbnailFilename Method.

Displaying 3D Maps

The Virtual Earth map control includes the ability to display a three-dimensional view of the world so that you can you to incorporate the same Virtual Earth 3D experience found at the Live Search Maps Web site into your own Web sites.

Enabling 3D maps

Because the three-dimensional map functionality is built in to the same map control as the standard two-dimensional maps, you do not need to change how you build your map-enabled Web site. You can program against the new 3D APIs in the same way that you use the 2D APIs. On the programming side, including the 3D maps in your existing sites requires very little additional effort.

However, because of the complexity and the graphics-intensive nature of the Virtual Earth 3D maps, software must be installed on the client computer, and the client computer must have sufficient hardware to display the maps. The software, called Virtual Earth 3D, requires the following on the client computer:

  • Microsoft Windows XP Service Pack 2, Microsoft Windows Server 2003, or Microsoft Windows Vista
  • Microsoft Internet Explorer 6 or Windows Internet Explorer 7, including 64-bit versions, or Mozzilla Firefox 2.0
  • Microsoft .NET Framework version 2.0
  • 250 MB or more of hard disk space
  • A 1.0 GHz processor (2.8 GHz or faster recommended)
  • 256 MB of system memory (1 GB recommended)
  • 32-MB video card (256 MB recommended) that supports Microsoft DirectX 9, with 3D hardware acceleration enabled
  • A high-speed or broadband Internet connection

Verifying the Requirements

Because there are several client-side requirements that users don’t need when viewing the standard two-dimensional maps, you should provide an appropriate user interface to verify that the Virtual Earth 3D control is installed. To do this, use the VEMap.AttachEvent Method to attach the VEMap.onmodenotavailable Event to your VEMap Class object. If the software is not yet installed on the client computer when the map mode is changed to 3D mode, this event fires. You can then provide instructions on installing the software.

For example, the following code creates a new VEMap object, attaches the onmodenotavailable event, and loads the map. When run on a computer without the software installed, the event handler is called when the map is switched to 3D mode. The event handler provides instructions to the customer on how to install the Virtual Earth 3D software.

map=null;
function onPageLoad()
{
   map = new VEMap('map');
   map.LoadMap();
   map.AttachEvent('onmodenotavailable', No3DInstalled);
}
function No3DInstalled ()
{
    alert('Before viewing the maps in 3D mode, '+
      'you must install the Virtual Earth 3D software on your computer.' +
      '\nTo install the software, visit ' +
      'http://go.microsoft.com/fwlink/?LinkId=72623.');
}

Note: The link to the installation program for the Virtual Earth 3D software (and its prerequisites) is http://go.microsoft.com/fwlink/?LinkId=72623.

Issues when Using 3D Mode

Because Virtual Earth 3D is an embedded control on your Web page, certain web-based events and properties behave differently from the traditional 2D maps. Consider the following situations when designing your site to use 3D maps:

  • Custom controls or Web elements that you display on top of a 2D map will be hidden behind the 3D map. You can prevent this by using an IFRAME “shim” for each control. For more information, see the VEMap.AddControl Method topic and code example.
  • The default find control is also hidden when the map mode is switched to 3D mode. To prevent this call the VEMap.ShowFindControl Method when the map mode is changed.
  • When the Virtual Earth 3D control has focus, it captures keyboard and mouse events and handles them. Map Control events are passed from the Virtual Earth 3D control, so you can continue to use all of them except VEMap.onstartpan Event. Page-level events will not fire when the Virtual Earth 3D control has focus.
  • Other map enhancements, including pushpins, custom pushpin and tile layers, polylines, and polygons work in both 2D and 3D mode maps.

Note: The client computer cannot have more than one instance of the 3D map running in the same process at the same time.

Disabling 3D maps

Because the additional requirements for displaying 3D maps, you may want to prevent users from switching to 3D mode. You can do this by setting the showSwitch parameter of the VEMap.LoadMap Method to false.


  • Recent Posts

  • Tags

  • Categories