Wednesday, October 24, 2012

Getting geolocation from IP address in Scala

I saw a post titled "Implement Geolocation using Scala and Lift" and thought it would be handy to have a method to grab the location outside of lift. So inorder to do this, you'll first need to go to IPInfoDB and get an API key. Once you have your key you can use the following method to get a JSON string with the geo-location of an IP address:
def ipInfo(name: String, key: String) = {
    val ip = java.net.InetAddress.getByName(name).getHostAddress
    val url = new java.net.URL("http://api.ipinfodb.com/v3/ip-city/?key=" + 
            key + "&ip=" + ip + "&format=json")
    val connection = url.openConnection
    val inputStream = connection.getInputStream
    val location = new String(Stream.continually(inputStream.read)
            .takeWhile(-1 !=).map(_.toByte).toArray)
    inputStream.close()
    location
}
Now to use it you just do the following:
val key = // your API key from IPInfoDB
val json = ipInfo("www.google.com", key)
Which will return something like:
json: java.lang.String = 
{
 "statusCode" : "OK",
 "statusMessage" : "",
 "ipAddress" : "216.239.32.27",
 "countryCode" : "US",
 "countryName" : "UNITED STATES",
 "regionName" : "CALIFORNIA",
 "cityName" : "MOUNTAIN VIEW",
 "zipCode" : "94043",
 "latitude" : "37.3861",
 "longitude" : "-122.084",
 "timeZone" : "-07:00"
}
Then you can use your favorite method of parsing JSON (maybe Jerkson?) into a Scala representation.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.