Defaulting a POINT to GeoIP

So you added a totally cool and gnarly view that lets the user specify a POINT on a map (and text coordinates), and then two more to let them view and explore them.  Your users should love you forever... but those dratted users are complaining that the default location is off in the Atlantic ocean off the coast of Africa.  The obvious solution, involving bricking ungrateful users into hidden rooms in catacombs is rejected due to the expense of acquiring catacombs, so what do you do?

How about using GeoIP localization to make the default location the (approximate) location from which the request is coming in?

import GeoIP
geo = GeoIP.open("/usr/share/GeoIP/GeoIPCity.dat",GeoIP.GEOIP_STANDARD)
georecord = geo.record_by_addr( request.META.get('REMOTE_ADDR') )
if georecord:
    if not gps:
        gps = 'SRID=4326;POINT(%(longitude)s %(latitude)s)' % georecord

You'll want to install the python-geoip and geoip-database-contrib packages on Ubuntu to get the database and the library.  The end result is that the map is located pretty close to where the user is sitting (normally), which is often approximately where they are trying to set the location.  You won't get results for non-public IP addresses, but oh well, there's always catacombs for sale somewhere.

For bonus points, the following:

if not location: 
    location = ', '.join([georecord[k] for k in ['city','region_name','country_name'] if k in georecord])

Gives them a default textual location description such as 'Toronto, Ontario, Canada'.  Of course, if we expected a lot of mobile users on our apps, we could also use the HTML5 GeoLocation API to get the coordinates, but that's another day.

Comments

Comments are closed.

Pingbacks

Pingbacks are closed.

Trackbacks