package com.glulogic.ernestmarples /** * * A Groovy function to return a latitude and longitude value from a postcode using the Ernest Marples API * * Important: Given the inherent unreliability of using a service like this, * it's probably sensible to contact the Ernest Marples team to let them know * you're using it so they can hang on to your email and let you know if anything important happens. * * Hopefully the Royal Mail will be nice, and license them to use the postcode database. * Then you'll be able to rely on it and this service will become a seamless and transparent * part of the web's infrastructure, like it ought to be. * * More information at http://www.ernestmarples.com * * Version: 0.1 * Date: August 2009 * Author: Wayne Keenan (wayne.keenan@gmail.com) * */ public class GeoCode { static def service = "http://ernestmarples.com/" static def responseFormat = /^([^,]+),(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?)\n/ static def lookup(postcode) { def params = "?p="+ URLEncoder.encode(postcode, "UTF-8") + "&f=csv" def response = new URL(service+params).text def matcher = ( response =~ responseFormat) if (matcher.matches()){ return [ postcode: matcher[0][1], latitude: matcher[0][2], longitude: matcher[0][3] ] } else { return [ error: true, errorText: "Response did not match expected format, expected $responseFormat, got= $response" ] } } // allow to be run from the command line: public static void main(String[] args) { if (args.length > 0) { println lookup(args[0]) } else { println "Usage: com.glulogic.ernestmarples.GeoCode [postcode]" } } }