Created
July 23, 2009 13:47
-
-
Save tomlea/152929 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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