As an aid for the Georgia Tech Hack 2010 and as a follow-up to my talk about geolocation here is a simple JavaScript library that answers most of your geo questions. It wraps the following services in a simple interface:
- Yahoo Placemaker
- Yahoo GeoPlanet
- jsonip.appspot.com
- IP location tools
- W3C Geo location
- Flickr.places.findByLatLon
Usage
To use the geo library, simply include it in your document. There is one simple method to use which is:
yqlgeo.get(what,callback)
- what
- is the thing you want to analyse - this could be the URL to a web document, a text, an IP, a pair of latitude and longitude information or "visitor" to detect the geographic location of the current visitor.
- callback
- is the callback method that will be called when there was a succesful retrieval of information. The data comes back as an object - if there was an error retrieving the information the data will be wrapped in an
error
property.
Check out the different use cases of the library below:
Getting the geographical location from a text
You can send an arbitrary text to the get()
method to find the geographical information in it:
yqlgeo.get('paris,fr',function(o){
alert(o.place.name+' ('+
o.place.centroid.latitude+','+
o.place.centroid.longitude+
')');
})
Getting the location information from lat/lon
You can get all kind of data from a latitude and longitude pair. You can either send them in as two parameters or as an array:
yqlgeo.get(33.748,-84.393,function(o){
alert(o.place.name + ',' + o.place.country.content);
})
yqlgeo.get([33.748,-84.393],function(o){
alert(o.place.name + ',' + o.place.country.content);
})
Get all the geo locations from a certain URL
You can scrape a certain document at a URL for geographical locations:
yqlgeo.get('http://icant.co.uk',function(o){
var out = '';
var all = o.place.length;
for(var i=0;i<all;i++){
out+=o.place[i].name+'\n';
};
alert(out);
});
Get the place from an IP number
yqlgeo.get('217.12.14.240',function(o){
alert(o.place.name + ',' + o.place.country.content +
' (' + o.place.centroid.latitude + ',' +
o.place.centroid.longitude + ')'
);
});
Find the user (using the W3C geolocation API and IP as a fallback)
yqlgeo.get('visitor',function(o){
if(o.error){
alert('No location found for user :('); // some IPs are not in the DB :(
} else {
alert(o.place.name + ',' + o.place.country.content +
' (' + o.place.centroid.latitude + ',' +
o.place.centroid.longitude + ')'
);
}
});
Download the library
You can get the library directly from here by saving this link or by getting the source code from GitHub.