July 16th, 2010
Google Map IP geolocation with two sticks and a bit of twine!
I found myself in a bit of sticky situation a couple of days ago. I wanted to map site visitors’ approximate location using Maxmind’s amazing free IP address geolocation database. I used the same database for one of my paywalls so I thought it would be a fifteen-minute kind of affair: getting site visitors’ IP address using and looking it up in the Geolitecity database, then encoding the results into a Google Maps url that would display the map on the site.
As anyone who’s worked with static Google Maps knows, you pass in a bunch of parameters (latitude, longitude, size, markers) on a url string and Google returns a map. The problem for me was that even if I managed to pass the requisite latitude and longitude coordinates to the page, the link itself would not end with .png, .gif, or .jpg, which meant that WordPress would not display it as an image.
I will spare you the cursing and hair pulling that ensued and instead delight you with the multi-part solution. I wrote a PHP script that takes a visitor’s IP address and looks up its latitude and longitude in the Maxmind database, formulates a syntactically correct Google Maps url request, and uses a header to redirect the browser there. In order to convince WordPress that I was adding an image, I used mod_rewrite in an .htaccess file to redirect requests for “here.jpg” to my PHP script, and voila! Success!