I’m working on a project right now that will use lots of addresses and the locations around them. So, I needed to start playing around with geocoding!  I’m planning on using Google Maps for all my mapping needs, so it made sense to use the Google Maps Geocoding API as well (there are certainly other ones you can use though) and I put together a quick Grails application to show a sample of the type of stuff I’m doing. You can see all the code for this sample Grails app (geocoder) on GitHub.

To see what’s really happening, take a look at the GeocodeService class.  This is where I’m taking the query from the controller and sending it to Google requesting either XML or JSON.  I then take specific parts of the result and put them in a map for easy access in my view.  I’m also using the new groovy.json.JsonSlurper class that is part of Groovy 1.8.  It makes working with JSON really easy!  Here’s an excert from that class:

def queryForJSON(String query) {
  def config = ConfigurationHolder.config
  String configUrlJSON = config.googleapi.url.json
  def urlJSON = new URL(configUrlJSON + removeSpaces(query))
  def geoCodeResultJSON = new JsonSlurper().parseText(urlJSON.getText())
  def jsonMap = [:]
  jsonMap.query = query
  jsonMap.lat = geoCodeResultJSON.results.geometry.location.lat[0]
  jsonMap.lng = geoCodeResultJSON.results.geometry.location.lng[0]
  jsonMap.address = geoCodeResultJSON.results.formatted_address[0]
  return jsonMap

Here’s the unit test for this service method:

void testQueryForJSON() {
  def result = service.queryForJSON("Times Square")
  assert "40.75659" == result.lat.toString()
  assert "-73.98626" == result.lng.toString()
  assert "Theater District - Times Square, New York, NY, USA" ==

Pretty simple to do this type of stuff with Groovy! Thanks for reading and let me know if you have any suggestions for working with geocoding!