Virtual Earth: Center Map to Shape during OnClick Event

Apr 24, 2008  • Mapping

Here’s a short, simple example of wiring up Virtual Earth to zoom/pan the map to showing the best fit to center on a specific Shape object that is clicked on by the user.

This example works in both 2D and 3D map modes.

<!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="http://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(); 


    /// Attach a handler to the Maps OnClick Event 
    map.AttachEvent("onclick", Map_OnClick); 

    /// Add a couple Pushpin Shapes to the map 
    var shape1 = new VEShape(VEShapeType.Pushpin, new VELatLong(49.74999, -99.71));

    shape1.SetTitle("Shape 1");

    shape1.SetDescription("Test Shape 1");

    map.AddShape(shape1); 


    var shape2 = new VEShape(VEShapeType.Pushpin, new VELatLong(39.74999, -96.71));

    shape2.SetTitle("Shape 2");

    shape2.SetDescription("Test Shape2");

    map.AddShape(shape2); 



    /// Add a Polygon Shape to the map 
    var shape3points = new Array();

    shape3points[shape3points.length] = new VELatLong(37.74999, -99.71);

    shape3points[shape3points.length] = new VELatLong(37.74999, -110.71);

    shape3points[shape3points.length] = new VELatLong(32.74999, -111.71);

    var shape3 = new VEShape(VEShapeType.Polygon, shape3points);

    shape3.HideIcon(); // Hide the Polygons Icon Image

    map.AddShape(shape3); 
} 

function Map_OnClick(e)
{

    // Check if a Shape was clicked

    if (e.elementID != null)

    {

        // Get a reference to the Shape that was clicked

        var shape = map.GetShapeByID(e.elementID); 



        // Set the MapView to the Shapes collection of VELatLong points

        // This will zoom and pan the map to the best view to show all the points of this Shape

        map.SetMapView(shape.GetPoints());

    }

}

</script>

</head>

<body onload="GetMap();">

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

</body>

</html>