Class: YahooGeocoder

Inherits:
Geocoder show all
Defined in:
lib/kamelopard/geocode.rb

Overview

Uses Yahoo's PlaceFinder geocoding service: developer.yahoo.com/geo/placefinder/guide/requests.html Google's would seem most obvious, but since it requires you to display results on a map, … I didn't want to have to evaluate other possible restrictions. The argument to the constructor is a PlaceFinder API key, but testing suggests it's actually unnecessary

Instance Method Summary collapse

Constructor Details

#initialize(key) ⇒ YahooGeocoder



26
27
28
29
30
31
32
# File 'lib/kamelopard/geocode.rb', line 26

def initialize(key)
    @api_key = key
    @proto = 'http'
    @host = 'where.yahooapis.com'
    @path = '/geocode'
    @params = { 'appid' => @api_key, 'flags' => 'J' }
end

Instance Method Details

#lookup(address) ⇒ Object

Returns an object built from the JSON result of the lookup, or an exception



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/kamelopard/geocode.rb', line 35

def lookup(address)
    # The argument can be a string, in which case PlaceFinder does the parsing
    # The argument can also be a hash, with several possible keys. See the PlaceFinder documentation for details
    # http://developer.yahoo.com/geo/placefinder/guide/requests.html
    http = Net::HTTP.new(@host)
    if address.kind_of? Hash then
        p = @params.merge address
    else
        p = @params.merge( { 'q' => address } )
    end
    q = p.map { |k,v| "#{ CGI.escape(k) }=#{ CGI.escape(v) }" }.join('&')
    u = URI::HTTP.build([nil, @host, nil, @path, q, nil])

    resp = Net::HTTP.get u
    parse_response resp
end

#parse_response(resp) ⇒ Object



52
53
54
55
56
# File 'lib/kamelopard/geocode.rb', line 52

def parse_response(resp)
    d = JSON.parse(resp)
    raise d['ErrorMessage'] if d['Error'].to_i != 0
    d
end