Saturday, January 8, 2011

Time from GeoNames' RESTful Web Service via JSON/AJAX

I needed a small gadget for my travel blog (which is not published yet) to display the current time where I am currently at. As I did not find a useful one, I decided to write my own, and soon found that offers a RESTful Web Service for this purpose.

GeoNames publishes its work under a Creative Commons Attribution 3.0 License.

Here's the code:
<script language="JavaScript">

var url = ""+
var jo = {}; // JSON Object
var req = new XMLHttpRequest(); "GET", url, true );
req.onreadystatechange = function () {
 if (req.readyState == 4 && req.status == 200) {
  jo = JSON.parse( req.responseText );
  document.getElementById("tt").innerHTML = jo.time;

<div id="tt">...wait</div> 

Short Explanation:
The URL of the GeoNames Service contains the latitude and longitude of the place where I will stay. That's implies the only drawback: I have to change this code, but I'm sure I won't change timezones every week.
The request is sent via HTTP, and the server asynchronously (i.e. AJAX) sends back the result, which is handled in the shown function. The response is a JSON object, that has an attribute time, which is finally written to a reserved region (the div at the bottom of the code).

Well, to demonstrate that it works -- that is the current time of Buenos Aires:

Note, that this method is not reliable, as it does not always work! Sometimes, the JSON-response contains a message like "Sorry, we cannot serve your request as our servers are busy". That's why I searched for another alternative, and found it here.

No comments:

Post a Comment