Getting geolocation from IP address in Scala

by 10/24/2012 10:53:00 PM 0 comments
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.

Brian Schlining

Developer

Cras justo odio, dapibus ac facilisis in, egestas eget quam. Curabitur blandit tempus porttitor. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.

0 comments: