Address geolocation in Groovy

It is really easy to consume JSON-producing API using Groovy. Need to get latiturde/longitude programmatically? Want to check an address?

Google GeoCoding API

The following snippets leverages the GeoCoding API from Google

import java.net.URL
import static java.net.URLEncoder.encode
import groovy.json.JsonSlurper

String inputAddress =
    "Piazza della Scala 1, Milano"

String serviceUrl =
    "http://maps.googleapis.com/maps/api/geocode/json?address=${encode(inputAddress)}&sensor=false"

def locations =
    new JsonSlurper()
        .parse(new URL(serviceUrl))   // Query the service
        .results.collect { l ->       // Collect results
            [address: l.formatted_address,
             lat: l.geometry.location.lat,
             lon: l.geometry.location.lng]
        }

println(locations)

// Output =>
//  [[address:Piazza della Scala, 20121 Milan, Italy,
//           lat:45.4668534, lon:9.1895746]]

The JsonSlurper is really a time-saver, the response is parsed into a List of Map and, thanks to Groovy, you are able to navigate into the parsed data-structure as you would do with an ad-hoc object hierarchy.

Geocode.io API

Recently I found about the Geocode.io geolocation service on HN. You can query addresses in bulk (via POST) or one address at time, as in the following example.

import java.net.URL
import static java.net.URLEncoder.encode
import groovy.json.JsonSlurper

String inputAddress =
    '350 5th Ave, New York, NY 10118'

String apiKey=
    "3dbd8d3ddfd58628ffb22f2238efb3d5ed2fd52" // Use your API-key

String serviceUrl =
    "http://api.geocod.io/v1/geocode?q=${encode(inputAddress)}&api_key=${apiKey}"

def locations =
    new JsonSlurper()
        .parse(new URL(serviceUrl))   // Query the service
        .results.collect { l ->       // Collect results
            [address: l.formatted_address,
             lat: l.location.lat,
             lon: l.location.lng]
        }

println(locations)

// Output =>
//  [[address:New York NY, 10118,
//      lat:40.748998, lon:-73.986467]]

The service seems very promising, but, unfortunately, it is not able to deal with with non-US addresses.

derived from