Drawing a circle in Bing Maps

johnWeeGo[1]I noticed my old code samples around the place are a little outdated so I created this little sample based off the Bing Maps iSDK today. This is a little helper function that calculates 360 points around the location provided at the given radius in KM. The co-ordinates are quite accurate and you will notice the effects of adding a circle at different Latitudes on the Mercator map.

bingmapcircle

Full source:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
   <head>
      <title>Circle Example Bing Maps</title>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
      <script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.2"></script>
      <script type="text/javascript">
          var map = null;
          var pinid = 0;

          function GetMap() {
              map = new VEMap('myMap');
              map.LoadMap();
              map.SetZoomLevel(2);
          }

          function AddPolyline() {
              var ll = map.GetCenter();
              var shape = new VEShape(VEShapeType.Polyline, getCircle(ll, 100));
              shape.SetTitle('My circle');
              shape.SetDescription('This is shape number ' + pinid);
              pinid++;
              map.AddShape(shape);
          }
          
          function getCircle(loc, radius) {
              var R = 6371; // earth's mean radius in km
              var lat = (loc.Latitude * Math.PI) / 180; //rad
              var lon = (loc.Longitude * Math.PI) / 180; //rad
              var d = parseFloat(radius) / R;  // d = angular distance covered on earth's surface
              var locs = new Array();
              for (x = 0; x <= 360; x++) {
                  var p2 = new VELatLong(0, 0)
                  brng = x * Math.PI / 180; //rad
                  p2.Latitude = Math.asin(Math.sin(lat) * Math.cos(d) + Math.cos(lat) * Math.sin(d) * Math.cos(brng));
                  p2.Longitude = ((lon + Math.atan2(Math.sin(brng) * Math.sin(d) * Math.cos(lat), Math.cos(d) - Math.sin(lat) * Math.sin(p2.Latitude))) * 180) / Math.PI;
                  p2.Latitude = (p2.Latitude * 180) / Math.PI;
                  locs.push(p2);
              }
              return locs;
          }

      
      </script>
   </head>
   <body onload="GetMap();">
      <div id='myMap' style="position:relative; width:400px; height:400px;"></div>
      <div><a href='#' onclick='AddPolyline();'>Add Circle</a></div>
   </body>
</html>
      

If you’re after a full toolkit of useful functions for Bing Maps you should check out the awesome: http://vetoolkit.codeplex.com/

Technorati Tags: ,