public
Last active

  • Download Gist
gistfile1.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.