Skip to content

Instantly share code, notes, and snippets.

@tomlea
Created July 23, 2009 13:47
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save tomlea/152929 to your computer and use it in GitHub Desktop.
require "json"
require "httpclient"
# Usage:
# reevoo_hq = LongLat.from_postcode("SE1 0RF")
# reevoo_hq.long # => -0.10276
# reevoo_hq.lat # => 51.500991
class LongLat
PostcodeLookupError = Class.new(RuntimeError)
attr_reader :long, :lat
def initialize(long, lat)
@long, @lat = long,lat
end
def self.from_postcode(postcode)
response = HTTPClient.get("http://ernestmarples.com/?p=#{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
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment