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 =
    val url = new"" + 
            key + "&ip=" + ip + "&format=json")
    val connection = url.openConnection
    val inputStream = connection.getInputStream
    val location = new String(Stream.continually(
            .takeWhile(-1 !=).map(_.toByte).toArray)
Now to use it you just do the following:
val key = // your API key from IPInfoDB
val json = ipInfo("", key)
Which will return something like:
json: java.lang.String = 
 "statusCode" : "OK",
 "statusMessage" : "",
 "ipAddress" : "",
 "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


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