]> git.openstreetmap.org Git - rails.git/blob - app/controllers/geocoder_controller.rb
f557668b69e812628e72f4eb12b44f023ea235da
[rails.git] / app / controllers / geocoder_controller.rb
1 class GeocoderController < ApplicationController
2   require 'uri'
3   require 'net/http'
4   require 'rexml/document'
5
6   def search
7     query = params[:query]
8     results = Array.new
9
10     if query.match(/^\d{5}(-\d{4})?$/)
11       results.push search_us_postcode(query)
12     elsif query.match(/(GIR 0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKS-UW])\s*[0-9][ABD-HJLNP-UW-Z]{2})/i)
13       results.push search_uk_postcode(query)
14     elsif query.match(/[A-Z]\d[A-Z]\s*\d[A-Z]\d/i)
15       results.push search_ca_postcode(query)
16     else
17       results.push search_osm_namefinder(query)
18       results.push search_geonames(query)
19     end
20
21     results_count = count_results(results)
22
23     render :update do |page|
24       if results_count == 1
25         position = results.collect { |s| s[:results] }.compact.flatten[0]
26         page.call "setPosition", position[:lat], position[:lon], position[:zoom]
27       else
28         page.replace_html :search_results_content, :partial => 'results', :object => results
29         page.call "openSearchResults"
30       end
31     end
32   end
33
34 private
35
36   def search_us_postcode(query)
37     results = Array.new
38
39     # ask geocoder.us (they have a non-commercial use api)
40     response = fetch_text("http://rpc.geocoder.us/service/csv?zip=#{URI.escape(query)}")
41
42     # parse the response
43     unless response.match(/couldn't find this zip/)
44       data = response.split(/\s*,\s+/) # lat,long,town,state,zip
45       results.push({:lat => data[0], :lon => data[1], :zoom => 12,
46                     :prefix => "#{data[2]}, #{data[3]}, ",
47                     :name => data[4]})
48     end
49
50     return { :source => "Geocoder.us", :url => "http://geocoder.us/", :results => results }
51   rescue Exception => ex
52     return { :source => "Geocoder.us", :url => "http://geocoder.us/", :error => "Error contacting rpc.geocoder.us: #{ex.to_s}" }
53   end
54
55   def search_uk_postcode(query)
56     results = Array.new
57
58     # ask npemap.org.uk to do a combined npemap + freethepostcode search
59     response = fetch_text("http://www.npemap.org.uk/cgi/geocoder.fcgi?format=text&postcode=#{URI.escape(query)}")
60
61     # parse the response
62     unless response.match(/Error/)
63       dataline = response.split(/\n/)[1]
64       data = dataline.split(/,/) # easting,northing,postcode,lat,long
65       results.push({:lat => data[3], :lon => data[4], :zoom => 12,
66                     :name => data[2].gsub(/'/, "")})
67     end
68
69     return { :source => "NPEMap / FreeThePostcode", :url => "http://www.npemap.org.uk/", :results => results }
70   rescue Exception => ex
71     return { :source => "NPEMap / FreeThePostcode", :url => "http://www.npemap.org.uk/", :error => "Error contacting www.npemap.org.uk: #{ex.to_s}" }
72   end
73
74   def search_ca_postcode(query)
75     results = Array.new
76
77     # ask geocoder.ca (note - they have a per-day limit)
78     response = fetch_xml("http://geocoder.ca/?geoit=XML&postal=#{URI.escape(query)}")
79
80     # parse the response
81     unless response.get_elements("geodata/error")
82       results.push({:lat => response.get_text("geodata/latt").to_s,
83                     :lon => response.get_text("geodata/longt").to_s,
84                     :zoom => 12,
85                     :name => query.upcase})
86     end
87
88     return { :source => "Geocoder.CA", :url => "http://geocoder.ca/", :results => results }
89   rescue Exception => ex
90     return { :source => "Geocoder.CA", :url => "http://geocoder.ca/", :error => "Error contacting geocoder.ca: #{ex.to_s}" }
91   end
92
93   def search_osm_namefinder(query)
94     results = Array.new
95
96     # ask OSM namefinder
97     response = fetch_xml("http://www.frankieandshadow.com/osm/search.xml?find=#{URI.escape(query)}")
98
99     # parse the response
100     response.elements.each("searchresults/named") do |named|
101       lat = named.attributes["lat"].to_s
102       lon = named.attributes["lon"].to_s
103       zoom = named.attributes["zoom"].to_s
104       place = named.elements["place/named"] || named.elements["nearestplaces/named"]
105       type = named.attributes["info"].to_s.capitalize
106       name = named.attributes["name"].to_s
107       description = named.elements["description"].to_s
108       if name.empty?
109         prefix = ""
110         name = type
111       else
112         prefix = "#{type} "
113       end
114       if place
115         distance = format_distance(place.attributes["approxdistance"].to_i)
116         direction = format_direction(place.attributes["direction"].to_i)
117         placename = place.attributes["name"].to_s
118         suffix = ", #{distance} #{direction} of #{placename}"
119       else
120         suffix = ""
121       end
122       results.push({:lat => lat, :lon => lon, :zoom => zoom,
123                     :prefix => prefix, :name => name, :suffix => suffix,
124                     :description => description})
125     end
126
127     return { :source => "OpenStreetMap Namefinder", :url => "http://www.frankieandshadow.com/osm/", :results => results }
128   rescue Exception => ex
129     return { :source => "OpenStreetMap Namefinder", :url => "http://www.frankieandshadow.com/osm/", :error => "Error contacting www.frankieandshadow.com: #{ex.to_s}" }
130   end
131
132   def search_geonames(query)
133     results = Array.new
134
135     # ask geonames.org
136     response = fetch_xml("http://ws.geonames.org/search?q=#{URI.escape(query)}&maxRows=20")
137
138     # parse the response
139     response.elements.each("geonames/geoname") do |geoname|
140       lat = geoname.get_text("lat").to_s
141       lon = geoname.get_text("lng").to_s
142       name = geoname.get_text("name").to_s
143       country = geoname.get_text("countryName").to_s
144       results.push({:lat => lat, :lon => lon, :zoom => 12,
145                     :name => name,
146                     :suffix => ", #{country}"})
147     end
148
149     return { :source => "GeoNames", :url => "http://www.geonames.org/", :results => results }
150   rescue Exception => ex
151     return { :source => "GeoNames", :url => "http://www.geonames.org/", :error => "Error contacting ws.geonames.org: #{ex.to_s}" }
152   end
153
154   def fetch_text(url)
155     return Net::HTTP.get(URI.parse(url))
156   end
157
158   def fetch_xml(url)
159     return REXML::Document.new(fetch_text(url))
160   end
161
162   def format_distance(distance)
163     return "less than 1km" if distance == 0
164     return "about #{distance}km"
165   end
166
167   def format_direction(bearing)
168     return "south-west" if bearing >= 22.5 and bearing < 67.5
169     return "south" if bearing >= 67.5 and bearing < 112.5
170     return "south-east" if bearing >= 112.5 and bearing < 157.5
171     return "east" if bearing >= 157.5 and bearing < 202.5
172     return "north-east" if bearing >= 202.5 and bearing < 247.5
173     return "north" if bearing >= 247.5 and bearing < 292.5
174     return "north-west" if bearing >= 292.5 and bearing < 337.5
175     return "west"
176   end
177
178   def count_results(results)
179     count = 0
180
181     results.each do |source|
182       count += source[:results].length if source[:results]
183     end
184
185     return count
186   end
187 end