Saturday, July 9, 2011

Location awareness with Django

A common problem faced by large, directory-based websites is that of directing their users to the most appropriate content. At Ekam.ca, we would like to show new users relevant businesses and events as soon as they land on the main page. One way to accomplish that, and this is used by many websites, is to prompt a user to select their location on their first visit. Prompting for input can be frustrating for new users and may result in a loss of page hits; the modern internet user wants his or her information quickly and has little patience for websites polling for personal information.

A second method, and the one we employ at Ekam.ca, is to use the client request data (specifically the client IP address) to determine the user's location and serve the appropriate information to the users without nagging them. The GeoIP geolocation library included with GeoDjango makes this task extremely simple. GeoDjango is a "world-class geographic web framework" that includes numerous other indispensable geo-spatial libraries and is included with the latest versions of Django (Django 1.3, 1.2).

Setting up GeoIP to obtain a user's city of origin can be accomplished with the following simple tasks:
  1. 1. Download the MaxMind city and IP address datasets that will be used by GeoIP.
  2. 2. Configure GeoIP to use said datasets.
  3. 3. Poll GeoIP using the request IP address to get the city of origin.

GeoIP requires a database to map IP addresses to cities and these must be obtained from an external source. The best (and free!) option is the MaxMind GeoIP dataset. To obtain these, simply download the two files GeoIP.dat.gz and GeoLiteCity.dat.gz inside your Django project. Note that you must download the datasets in binary formats, GeoIP does not currently support CSV.

Next, unzip the two datasets using the commands:



GeoIP also needs to be told where to find these datasets, and this can be specified by setting the GEOIP_PATH in your Django project's settings.py file.

Finally, the GeoIP API can now be used to determine the user's city using the following short snipet of code:



And that's it! You can now determine where your users are from and direct them to the most appropriate section of your website without any need for annoying popups.

2 comments:

  1. This comment has been removed by a blog administrator.

    ReplyDelete
  2. This comment has been removed by a blog administrator.

    ReplyDelete