Tuesday, January 25, 2011

Sample AJAX Web Application for FCO Travel Advisory Service

We published Foreign & Commonwealth Office data recently and here is a short sample that shows you how these data can be used from your own application.

I decided to create a sample AJAX based web application that displays UK embassies on a map as you can see on the following picture.


Create this app in two steps


I started with empty html file. As I use jQuery and Bing Maps, I added links to javascript files in my header. Then I added an onload function that loads the default map.

<html>
<head>

  <script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.4.min.js" ></script>
  <script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.2"></script>  

  <script type="text/javascript">
    $(document).ready(function () {
      // load map
      map = new VEMap('myMap');         
      map.LoadMap();
    });
  </script>

</head>
<body>
  <div id='myMap' style="position:relative; width:100%; height:100%;"></div>
</body>
</html>

The second step is to add the code that uses our service and loads the embassy data. I added the following script block after the first one. It uses JQuery to asynchronously load the data from our OData service. Once the data are loaded it loops through the records and creates a new push pin for each embassy with its latitude and longitude.

<script type="text/javascript">
  $(document).ready(function () {
    // load embassy positions
    var url = "http://traveladvisor.cloudapp.net/TravelAdvisorService.svc/Embassies";
    $.getJSON(url, ProcessData);
  });
 
  function ProcessData(result)
  {
    // for each embassy 
    for (var id in result.d)
    {
      // create new pushpin on the map
      var embassy = result.d[id];
      AddPushpin(embassy.Lat, embassy.Long, embassy.Title);
    }
  }
 
  function AddPushpin(latitude, longitude, title)
  {
    // ignore invalid latitude or longitude
    if (isNaN(latitude) || isNaN(latitude))
      return;
 
    // add pushpin
    var position = new VELatLong(latitude, longitude);
    var pushpin  = new VEShape(VEShapeType.Pushpin, position);
    pushpin.SetTitle(title);
    map.AddShape(pushpin);
  }
</script>

And that’s all, open your file in browser and you will get the result as seen on the screenshot above.

4 comments:

  1. This comment has been removed by a blog administrator.

    ReplyDelete
  2. This comment has been removed by a blog administrator.

    ReplyDelete
  3. Hey nice blog,Thank's for this helpful information come back again for more interesting information…Keep it up!
    Taxi in Agra

    ReplyDelete