Using geolocation is something that people are doing a lot lately. You may have noticed twitter.com in FireFox showing a little bar at the top asking if it’s alright to share your location. This is so that when you tweet you can have your location show up there. That way you can keep track of where you tweet from. There are many uses for this kind of information and these days there’s a lot of free things out there to help you get started with your geolocation project.
Installing GeoIP
Requirements/Dependancies:
- Python 2.4+
- python-geoip
- libc6
- libgeoip1
More on dependencies here http://ns2.canonical.com/es/karmic/python-geoip. But don’t worry about these since most of them get installed by the package anyway.
A couple of basic principles before we get started.
- Geolocation is gathered from an IP address.
- There has to be a database that connects the IP address to a geographical location
I’m going to be using Python here because frankly it’s powerful, easy and has awesome libraries for geolocation. Which brings me to the GeoIP library! I’m using Ubuntu 9.10 so most of these libraries will just take an apt-get to install.
Then you can install python-geoip with
sudo apt-get install python-geoip
Or you can get the source from http://geolite.maxmind.com/download/geoip/api/python/
Now that you have this installed you can test it with the following code put in the python terminal.
>>> import GeoIP
>>> gi = GeoIP.new(GeoIP.GEOIP_MEMORY_CACHE)
>>> print gi.country_code_by_addr("203.195.93.0")
I got that from MaxMind’s tutorial http://www.maxmind.com/app/python. At this point you have the ability to track IPs down to the country level. What you probably really want is to go down to the city level.
Geolocation – Cities
If you call some of the other functions on the GeoIP class like record_by_addr() you’lld get an error like this
“Invalid database type GeoIP Country Edition, expected GeoIP City Edition, Rev 1″

