Home > Groovy > accessing Google geocode api with groovy

accessing Google geocode api with groovy

This is just a quick post on how you can get started with the google geocode API services from groovy

you start by visiting Google set to get an authentication key


use the ‘get a key’ button in the second section. this runs a wizard for you and you complete your details. I set up a server key for dev pc as i’m playing and that’s the registered server name i used.

At the end of this process google will generate an API key for you which you should record safely and securely. when coding read this value from a config file, etc so that you don’t encode it directly in your code.

Once setup with this you try the API out. There is a interactive javascript version of this api which i havent used – i’m using the json webservice, and there is an XML version of the service also.

The return result type has been encoded into the base URL, and not using accept headers.

first lets start with location class, that you’ll provide instance of with the address you want to get lat/long for. (you can do this in reverse as well)

class Location {
String houseNumber
String street
String city
String state
String zip
String country

double latitude
double longitude

String toString () {"$street, $city, $zip, $state, $country : latitude:$latitude, longitude:$longitude"}

i’m not persisting this put you do so readily as local cache etc.

The web service is located with a url base of

 def base = "https://maps.googleapis.com/maps/api/geocode/json?"

what the geocoder service will do is take a location (with populated record details) and build an address parameter, by URLencoding an array of address data from the location, using the join(‘,’) as the separator.

You then creat a params array for the web service, by taking a map of the address and your server API key (there is an optional components attribute that i have not used here – see google api defn for details). you then collect and join the key=value pairs you build to get the resultant param format for the call.

you then use JsonSlurper to parse the result of the call, (assert it all went ok), and then read the lat, lng values back (google api shows you the structure of the result set) and store these back in the location instance, converting the result to Double as you do so.

class Geocoder {
    def base = "https://maps.googleapis.com/maps/api/geocode/json?"

    void completeLatLong (Location loc){
        def addressFields =  loc.street ? [loc.street,loc.city,loc.zip,loc.state,loc.country] : [loc.city, loc.country]
        def address = addressFields.collect {URLEncoder.encode (it, 'UTF-8')}.join (',')
        def params = [address:address,
                      key:<your api key here>]
        def url = base +params.collect {k,v -> "$k=$v"}.join ('&')

        def response = new JsonSlurper().parse (url.toURL())

        assert response.status == "OK"
        loc.latitude = response.results[0].geometry.location.lat.toDouble()
        loc.longitude = response.results[0].geometry.location.lng.toDouble ()


you can now write tests, or simple driver script to use the service (fill in your own street, city, etc.

def loc = [street: "<your street>", city: "<your city>", zip: "<your zip>", state:"<your state>", country:"<your country>"] as Location

def geo = new Geocoder()
geo.completeLatLong (loc)

println loc  //should return completed lat/long from the successful service 

This should return you the loc record with the added geocoding details, which you can use elsewhere

Categories: Groovy
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: