Class: MapquestGeocoder

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

Instance Attribute Summary collapse

Attributes inherited from Geocoder

#host, #params, #path

Instance Method Summary collapse

Methods inherited from Geocoder

#processParam

Constructor Details

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

Returns a new instance of MapquestGeocoder.


61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/kamelopard/geocode.rb', line 61

def initialize(key, response_format = 'json')
    super()
    @proto = 'http'
    @host = 'www.mapquestapi.com'
    @path = {
        :address => '/geocoding/v1/address',
        :batch => '/geocoding/v1/batch'
    }
    @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


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

def api_key
  @api_key
end

#response_formatObject (readonly)

Returns the value of attribute response_format


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

def response_format
  @response_format
end

Instance Method Details

#getURL(args, type) ⇒ Object


74
75
76
77
78
79
80
81
82
83
84
# File 'lib/kamelopard/geocode.rb', line 74

def getURL(args, type)
    raise "Type (#{type}) must be one of #{ @path.keys.map { |a| ":#{a}" }.join(', ')}" unless @path.has_key? type

    params = @params.map { |k, v| processParam(v, k) }.concat(args).join('&')

    http = Net::HTTP.new(@host)
    u = URI::HTTP.build([nil, @host, nil, @path[type], params, nil])

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

#lookup(address) ⇒ Object

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


87
88
89
90
91
92
# File 'lib/kamelopard/geocode.rb', line 87

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
    return getURL(processParam(address), :address)
end

#lookupBatch(addresses) ⇒ Object


94
95
96
97
# File 'lib/kamelopard/geocode.rb', line 94

def lookupBatch(addresses)
    # The argument should be an array of the same sorts of values that can be fed to lookup()
    return getURL(addresses.map { |k| processParam(k) }.flatten(1), :batch)
end

#parse_response(r) ⇒ Object


99
100
101
102
103
# File 'lib/kamelopard/geocode.rb', line 99

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