Monthly Archives: February 2011

Location awareness with GeoLiteCity and Rails

So you want to make your app location-aware. There are a number of different ways to do this (Quova,, geokit, etc), but one of the most popular seems to be MaxMind’s GeoIP databases. They have a free version which is unsupported and less accurate than their subscription version, but the interface and process seems to be essentially the same.

First, we have to get the C version of the api installed and working:
tar xvzf GeoIP-1.4.6.tar.gz
cd GeoIP-1.4.6
make && sudo make install

Then we’re going to grab Ryan Dahl’s geoip_city gem.
sudo gem install geoip_city

And we’re almost there. Now all we have to do is instantiate the database using the free data from MaxMind, and query it.
require 'rubygems'
require 'geoip_city'
db ='config/GeoLiteCity.dat')
{ :longitude=>-122.966697692871, 

Note that this uses MaxMind’s C database which was designed for this application. It _is_ possible to move the data into an sql database and query it from there, but MaxMind says that the custom database is much faster at querying, and somebody seems to have confirmed it.

Also: do NOT reinstantiate the db on every request if you are using Rails. It’s a hefty 35mb, and though it will be garbage collected, a couple of quick requests before the garbage collector runs could easily bloat your app into emergency shutdown panic.