Jon AtkinsonI'm a web developer and system administrator

Obtaining GeoIP location with YQL using Python

Posted on 20th April 2010. Tagged as gps, django, python, mobile, yql, location

I've a few projects coming up for 84labs which required location awareness. Location awareness works great with any recent phone, but for traditional clients, I needed to fall-back to obtaining the location from the client's IP address.

There is an excellent free IP location database hosted on datatables.org, which offered the easiest way to get the data which I needed. This meant using YQL, which I haven't used before; YQL is "an expressive SQL-like language that lets you query, filter, and join data across Web services".

So here is the code. I was using Python, Django and Python YQL module, but the same query presumably works with any language you choose. I've removed a lot of exception handling for clarity.

# Get the current user's IP address.
client_ip_address = request.META['REMOTE_ADDR']

# Create a YQL public query object.
y = yql.Public()

# Build the query.
query = 'USE "http://www.datatables.org/iplocation/ip.location.xml" AS ip.location; select * from geo.places where woeid in (select place.woeid from flickr.places where (lat,lon) in(select Latitude,Longitude from ip.location where ip="%s"))' % client_ip_address;

# Execute the query.
result = y.execute(query)

# ... et voila.
ip_place_name = result.rows['locality1']['content']
ip_location = result.rows['centroid']

That's it. The query just performs a simple select against the 'iplocation' database, then retrieves the latitude and longitude from the flickr.places database (flickr.places is part of the standard YQL set of databases, which is why we don't need a specific USE statement to be able to access it).

blog comments powered by Disqus

Twitter

There was a problem retrieving Jon's recent Tweets from Twitter. If you're really interested, you can visit twitter.com/jon_atkinson/

About Me

Picture of Jon Atkinson

Jon Atkinson is a web developer, sysadmin and occasional business guy. He works in the north west of England.

Jon can be contacted at , or on freenode as JonA. Also available: twitter, LinkedIn and Github.

My Company

I'm a director of FARM Digital, a company which provides bespoke web and mobile development for all kinds of businesses.

If you're interested in working with me, take a look, then contact me via FARM.