Module: Ym4r::YahooMaps::BuildingBlock::Geocoding

Defined in:
lib/ym4r/yahoo_maps/building_block/geocoding.rb

Defined Under Namespace

Classes: Result

Class Method Summary collapse

Class Method Details

.get(param) ⇒ Object

Sends a request to the Yahoo! Maps geocoding service and returns the result in an easy to use Ruby object, hiding the creation of the query string and the XML parsing of the answer.



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/ym4r/yahoo_maps/building_block/geocoding.rb', line 11

def self.get(param)
  unless param.has_key?(:street) or
      param.has_key?(:city) or
      param.has_key?(:state) or
      param.has_key?(:zip) or
      param.has_key?(:location)
    raise MissingParameterException.new("Missing location data for the Yahoo! Maps Geocoding service")
  end
  
  url = "http://api.local.yahoo.com/MapsService/V1/geocode?appid=#{Ym4r::YahooMaps::APP_ID}&"
  url << "street=#{param[:street]}&" if param.has_key?(:street)
  url << "city=#{param[:city]}&" if param.has_key?(:city)
  url << "state=#{param[:state]}&" if param.has_key?(:state)
  url << "zip=#{param[:zip]}&" if param.has_key?(:zip)
  url << "location=#{param[:location]}&" if param.has_key?(:location)
  url << "output=xml"
  
  begin
    xml = open(URI.encode(url)).read
  rescue OpenURI::HTTPError => error
    raise BadRequestException.new(error.to_s)
  rescue
    raise ConnectionException.new("Unable to connect to Yahoo! Maps Geocoding service")
  end
  
  doc = REXML::Document.new(xml) 
  
  if doc.root.name == "Error"
    raise RateLimitExceededException.new("Rate limit exceeded for Yahoo! Maps Geocoding service")
  else
    results = []
    doc.elements.each("//Result") do |result|
      data = result.elements
      results << Geocoding::Result.new(result.attributes['precision'],
                                       result.attributes['warning'],
                                       data['Latitude'].text.to_f,
                                       data['Longitude'].text.to_f,
                                       data['Address'].text,
                                       data['City'].text,
                                       data['State'].text,
                                       data['Zip'].text,
                                       data['Country'].text)
    end
    results
  end
end