Class: MapquestGeocoder

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

Overview

Some specific geocoding API classes follow. 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, or require that they be imposed on Kamelopard users.

Instance Attribute Summary collapse

Attributes inherited from Geocoder

#host, #params, #path

Instance Method Summary collapse

Constructor Details

#initialize(key, response_format = 'json') ⇒ MapquestGeocoder

Returns a new instance of MapquestGeocoder.



29
30
31
32
33
34
35
36
37
# File 'lib/kamelopard/geocode.rb', line 29

def initialize(key, response_format = 'json')
    super()
    @proto = 'http'
    @host = 'www.mapquestapi.com'
    @path = '/geocoding/v1/address'
    @api_key = key
    @response_format = response_format
    @params['key'] = @api_key
end

Instance Attribute Details

#api_keyObject (readonly)

Returns the value of attribute api_key.



27
28
29
# File 'lib/kamelopard/geocode.rb', line 27

def api_key
  @api_key
end

#response_formatObject (readonly)

Returns the value of attribute response_format.



27
28
29
# File 'lib/kamelopard/geocode.rb', line 27

def response_format
  @response_format
end

Instance Method Details

#lookup(address) ⇒ Object

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



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/kamelopard/geocode.rb', line 40

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( { 'location' => address } )
    end
    q = p.map { |k,v| "#{ k == 'key' ? k : CGI.escape(k) }=#{ k == 'key' ? v : 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(r) ⇒ Object



57
58
59
60
61
# File 'lib/kamelopard/geocode.rb', line 57

def parse_response(r)
    d = JSON.parse(r)
    raise d['info']['messages'].join(', ') if d['info']['statuscode'] != 0
    d
end