Geolocate visitors to your Rails App

March 24th, 2008 | by matt |

In modern web apps, knowing the location of your customer can be very important. A friend and I are developing a location-based service right now. I whipped up the following Ruby code that uses the hostip.info API to fetch a user’s location based on his IP address.

require ‘net/http’

def geoip(ip)
  begin
    res=Net::HTTP.get(URI.parse(”http://api.hostip.info/get_html.php?ip=#{ip}&position=true”))
    resarr = res.split(”\n”)
    pos = { :country => resarr[0].split(”: “)[1],
            :city => resarr[1].split(”: “)[1].split(”,”)[0],
            :state => resarr[1].split(”, “)[1],
            :lat => resarr[2].split(”: “)[1],
            :lng => resarr[3].split(”: “)[1]}
  rescue SocketError, Errno::ECONNREFUSED => e
    pos = nil
  end
end

This method takes an ip address. When calling this method, use Rails’ built-in method for determining the originating IP address, request.remote_ip.

location = geoip(request.remote_ip)