Sunday, June 20, 2010

Part III: getting the name of your location via geonames.org

Geonames.org provides an API for accessing geolocal information. For instance, given a latitude and longitude you can access the name of the closest geographical location. One problem I faced is the need of accessing geonames with a javascript code downloaded from my own server. This is traditionally prevented by XMLHttpRequest which is constrained by the Same Origin Policy. Therefore, I reverted to JsonRequest that supports safe cross-site communication. Luckly, Geonames supports JSON web service requests.

Here is the code
function processLocation1(jData){
if (jData == null) {
// There was a problem parsing search results
alert("Error parsing geoname data");
return;
}
locationData = 'just arrived close to ' + jData.geonames[0].name + ' in ' + jData.geonames[0].adminName1 + ', ' + jData.geonames[0].countryName;
}

function geonameRequest(request){
// Create a new script object
aObj = new JSONscriptRequest(request);
// Build the script tag
aObj.buildScriptTag();
// Execute (add) the script tag
aObj.addScriptTag();
}

function reverseGeonameLookup(){
var request1 = 'http://ws.geonames.org/findNearbyPlaceNameJSON?lat=' + lat + '&lng=' + lng + '&callback=processLocation1';
geonameRequest(request1);
}

No comments:

Post a Comment