Skip to content

Instantly share code, notes, and snippets.

Created July 23, 2009 13:47
What would you like to do?
require "json"
require "httpclient"
# Usage:
# reevoo_hq = LongLat.from_postcode("SE1 0RF")
# reevoo_hq.long # => -0.10276
# # => 51.500991
class LongLat
PostcodeLookupError =
attr_reader :long, :lat
def initialize(long, lat)
@long, @lat = long,lat
def self.from_postcode(postcode)
response = HTTPClient.get("{postcode.gsub(/[^a-zA-Z0-9]/, "")}&f=json")
raise PostcodeLookupError, "Lookup failed" unless response.contenttype.include?("application/json")
data = JSON.parse(response.content)
raise PostcodeLookupError, "No such postcode" unless data["long"] and data["lat"] and data["long"].length > 0 and data["lat"].length > 0
new data["long"].to_f, data["lat"].to_f
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment