Created
July 10, 2010 09:56
-
-
Save mumoshu/470603 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
#!/usr/bin/ruby -Ku | |
require "rubygems" | |
require "json" | |
require "net/http" | |
require "uri" | |
require "delegate" | |
Net::HTTP.version_1_2 | |
class Response | |
attr_reader :status, :results | |
def initialize(api_response) | |
@status = api_response["status"] | |
@results = Results.new(api_response["results"].map! {|r| Result.new(r) }) | |
end | |
def ok? | |
@status == "OK" | |
end | |
def not_ok? | |
not ok? | |
end | |
def over_query_limit? | |
@status == "OVER_QUERY_LIMIT" | |
end | |
def finest | |
@results.finest | |
end | |
end | |
class Results < DelegateClass(Array) | |
def initialize(ary) | |
super(ary) | |
end | |
def finest | |
reject {|x| x.postal_code? or x.route? }.first | |
end | |
end | |
class Result | |
attr_reader :types, :formatted_address, :address_components, :geometry | |
def initialize(result) | |
@types = result["types"] | |
@formatted_address = result["formatted_address"] | |
@address_components = result["address_components"] | |
@geometry = result["geometry"] | |
end | |
def postal_code? | |
@types.include? "postal_code" | |
end | |
def route? | |
@types.include? "route" | |
end | |
def sublocality? | |
@types.include? "sublocality" | |
end | |
end | |
class HttpGeocoder | |
def initialize(httpClass=Net::HTTP) | |
@httpClass = httpClass | |
end | |
def get(lat,lng) | |
uri_str = "http://maps.google.com/maps/api/geocode/json?latlng=#{lat},#{lng}&sensor=false" | |
uri = URI.parse(uri_str) | |
header = { | |
"Accept-Language" => "ja" | |
} | |
request_path = uri.path + "?" + uri.query | |
@httpClass.start(uri.host, uri.port) {|http| | |
response = http.get(request_path, header) | |
response.body | |
} | |
end | |
end | |
class HttpGeocoderStub | |
def initialize(response_body) | |
@res = response_body | |
end | |
def get(lat,lng) | |
@res | |
end | |
end | |
module DefaultProxies | |
@@proxy_port = "8080" | |
def self.proxy1 | |
Net::HTTP.Proxy("proxy.host.name", @@proxy_port) | |
end | |
def self.none | |
Net::HTTP | |
end | |
end | |
class ReverseGeocoder | |
def initialize(httpGeocoder) | |
@http_geocoder = httpGeocoder | |
end | |
def get(lat,lng) | |
json = JSON.parse(@http_geocoder.get(lat,lng)) | |
Response.new(json) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment