Geocoding with the Rails GeoKit Plugin
To retrieve a user's IP address, pass request.remote_ip into the IpGeocoder.geocode method. Doing so will return GeoKit's GeoLoc object, which includes a number of attributes, among them city, state, and even street_address. Consider the following controller method:
def ip @user_location = IpGeocoder.geocode(request.remote_ip) end
You then could access the city within the view, like so:
It appears you're located in <%= @user_location.city %>.
Keep in mind that although this feature can be very useful, it isn't foolproof. Remember,GeoKit relies on Hostip.info to determine the location based on an IP address, and even though Hostip.info's database is massive (over 8.5 million entries and counting), it is by no means complete. For instance, Hostip.info was unable to identify my location in downtown Columbus, Ohio, although tests with known IP addresses from other cities worked fine. If your IP address isn't found, be sure to take a moment and add it through the Hostip.info website.
Where to From Here?
With the geocoder component in place, you now have a complete mapping solution at your disposal. But, why stop here? In the next installment of this series, I'll show you how to add interactive features to your maps, giving your users a variety of exciting new ways to take advantage of your application!
About the Author
W. Jason Gilmore is a freelance developer, consultant, and technical writer. He's the author of several books, including the best-selling Beginning PHP and MySQL: From Novice to Professional, Third Edition (Apress, 2008. 1,080pp.).
Page 3 of 3