]> git.openstreetmap.org Git - rails.git/blob - app/controllers/geocoder_controller.rb
Add a warning about whitelisting webmaster@openstreetmap.org in antispam
[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       results.push search_osm_namefinder(query)
15     elsif query.match(/[A-Z]\d[A-Z]\s*\d[A-Z]\d/i)
16       results.push search_ca_postcode(query)
17     else
18       results.push search_osm_namefinder(query)
19       results.push search_geonames(query)
20     end
21
22     results_count = count_results(results)
23
24     render :update do |page|
25       page.replace_html :sidebar_content, :partial => 'results', :object => results
26
27       if results_count == 1
28         position = results.collect { |s| s[:results] }.compact.flatten[0]
29         page.call "setPosition", position[:lat].to_f, position[:lon].to_f, position[:zoom].to_i
30       else
31         page.call "openSidebar"
32       end
33     end
34   end
35   
36   def description
37     results = Array.new
38
39     lat = params[:lat]
40     lon = params[:lon]
41
42     results.push description_osm_namefinder("cities", lat, lon, 2)
43     results.push description_osm_namefinder("towns", lat, lon, 4)
44     results.push description_osm_namefinder("places", lat, lon, 10)
45     results.push description_geonames(lat, lon)
46
47     render :update do |page|
48       page.replace_html :sidebar_content, :partial => 'results', :object => results
49       page.call "openSidebar"
50     end
51   end
52
53 private
54
55   def search_us_postcode(query)
56     results = Array.new
57
58     # ask geocoder.us (they have a non-commercial use api)
59     response = fetch_text("http://rpc.geocoder.us/service/csv?zip=#{escape_query(query)}")
60
61     # parse the response
62     unless response.match(/couldn't find this zip/)
63       data = response.split(/\s*,\s+/) # lat,long,town,state,zip
64       results.push({:lat => data[0], :lon => data[1],
65                     :zoom => APP_CONFIG['postcode_zoom'],
66                     :prefix => "#{data[2]}, #{data[3]}, ",
67                     :name => data[4]})
68     end
69
70     return { :source => "Geocoder.us", :url => "http://geocoder.us/", :results => results }
71   rescue Exception => ex
72     return { :source => "Geocoder.us", :url => "http://geocoder.us/", :error => "Error contacting rpc.geocoder.us: #{ex.to_s}" }
73   end
74
75   def search_uk_postcode(query)
76     results = Array.new
77
78     # ask npemap.org.uk to do a combined npemap + freethepostcode search
79     response = fetch_text("http://www.npemap.org.uk/cgi/geocoder.fcgi?format=text&postcode=#{escape_query(query)}")
80
81     # parse the response
82     unless response.match(/Error/)
83       dataline = response.split(/\n/)[1]
84       data = dataline.split(/,/) # easting,northing,postcode,lat,long
85       postcode = data[2].gsub(/'/, "")
86       zoom = APP_CONFIG['postcode_zoom'] - postcode.count("#")
87       results.push({:lat => data[3], :lon => data[4], :zoom => zoom,
88                     :name => postcode})
89     end
90
91     return { :source => "NPEMap / FreeThePostcode", :url => "http://www.npemap.org.uk/", :results => results }
92   rescue Exception => ex
93     return { :source => "NPEMap / FreeThePostcode", :url => "http://www.npemap.org.uk/", :error => "Error contacting www.npemap.org.uk: #{ex.to_s}" }
94   end
95
96   def search_ca_postcode(query)
97     results = Array.new
98
99     # ask geocoder.ca (note - they have a per-day limit)
100     response = fetch_xml("http://geocoder.ca/?geoit=XML&postal=#{escape_query(query)}")
101
102     # parse the response
103     if response.get_elements("geodata/error").empty?
104       results.push({:lat => response.get_text("geodata/latt").to_s,
105                     :lon => response.get_text("geodata/longt").to_s,
106                     :zoom => APP_CONFIG['postcode_zoom'],
107                     :name => query.upcase})
108     end
109
110     return { :source => "Geocoder.CA", :url => "http://geocoder.ca/", :results => results }
111   rescue Exception => ex
112     return { :source => "Geocoder.CA", :url => "http://geocoder.ca/", :error => "Error contacting geocoder.ca: #{ex.to_s}" }
113   end
114
115   def search_osm_namefinder(query)
116     results = Array.new
117
118     # ask OSM namefinder
119     response = fetch_xml("http://gazetteer.openstreetmap.org/namefinder/search.xml?find=#{escape_query(query)}")
120
121     # parse the response
122     response.elements.each("searchresults/named") do |named|
123       lat = named.attributes["lat"].to_s
124       lon = named.attributes["lon"].to_s
125       zoom = named.attributes["zoom"].to_s
126       place = named.elements["place/named"] || named.elements["nearestplaces/named"]
127       type = named.attributes["info"].to_s.capitalize
128       name = named.attributes["name"].to_s
129       description = named.elements["description"].to_s
130
131       if name.empty?
132         prefix = ""
133         name = type
134       else
135         prefix = "#{type} "
136       end
137
138       if place
139         distance = format_distance(place.attributes["approxdistance"].to_i)
140         direction = format_direction(place.attributes["direction"].to_i)
141         placename = format_name(place.attributes["name"].to_s)
142         suffix = ", #{distance} #{direction} of #{placename}"
143
144         if place.attributes["rank"].to_i <= 30
145           parent = nil
146           parentrank = 0
147           parentscore = 0
148
149           place.elements.each("nearestplaces/named") do |nearest|
150             nearestrank = nearest.attributes["rank"].to_i
151             nearestscore = nearestrank / nearest.attributes["distance"].to_f
152
153             if nearestrank > 30 and
154                ( nearestscore > parentscore or
155                  ( nearestscore == parentscore and nearestrank > parentrank ) )
156               parent = nearest
157               parentrank = nearestrank
158               parentscore = nearestscore
159             end
160           end
161
162           if parent
163             parentname = format_name(parent.attributes["name"].to_s)
164
165             if  place.attributes["info"].to_s == "suburb"
166               suffix = "#{suffix}, #{parentname}"
167             else
168               parentdistance = format_distance(parent.attributes["approxdistance"].to_i)
169               parentdirection = format_direction(parent.attributes["direction"].to_i)
170               suffix = "#{suffix} (#{parentdistance} #{parentdirection} of #{parentname})"
171             end
172           end
173         end
174       else
175         suffix = ""
176       end
177
178       results.push({:lat => lat, :lon => lon, :zoom => zoom,
179                     :prefix => prefix, :name => name, :suffix => suffix,
180                     :description => description})
181     end
182
183     return { :source => "OpenStreetMap Namefinder", :url => "http://gazetteer.openstreetmap.org/namefinder/", :results => results }
184   rescue Exception => ex
185     return { :source => "OpenStreetMap Namefinder", :url => "http://gazetteer.openstreetmap.org/namefinder/", :error => "Error contacting gazetteer.openstreetmap.org: #{ex.to_s}" }
186   end
187
188   def search_geonames(query)
189     results = Array.new
190
191     # ask geonames.org
192     response = fetch_xml("http://ws.geonames.org/search?q=#{escape_query(query)}&maxRows=20")
193
194     # parse the response
195     response.elements.each("geonames/geoname") do |geoname|
196       lat = geoname.get_text("lat").to_s
197       lon = geoname.get_text("lng").to_s
198       name = geoname.get_text("name").to_s
199       country = geoname.get_text("countryName").to_s
200       results.push({:lat => lat, :lon => lon,
201                     :zoom => APP_CONFIG['geonames_zoom'],
202                     :name => name,
203                     :suffix => ", #{country}"})
204     end
205
206     return { :source => "GeoNames", :url => "http://www.geonames.org/", :results => results }
207   rescue Exception => ex
208     return { :source => "GeoNames", :url => "http://www.geonames.org/", :error => "Error contacting ws.geonames.org: #{ex.to_s}" }
209   end
210
211   def description_osm_namefinder(types, lat, lon, max)
212     results = Array.new
213
214     # ask OSM namefinder
215     response = fetch_xml("http://gazetteer.openstreetmap.org/namefinder/search.xml?find=#{types}+near+#{lat},#{lon}&max=#{max}")
216
217     # parse the response
218     response.elements.each("searchresults/named") do |named|
219       lat = named.attributes["lat"].to_s
220       lon = named.attributes["lon"].to_s
221       zoom = named.attributes["zoom"].to_s
222       place = named.elements["place/named"] || named.elements["nearestplaces/named"]
223       type = named.attributes["info"].to_s
224       name = named.attributes["name"].to_s
225       description = named.elements["description"].to_s
226       distance = format_distance(place.attributes["approxdistance"].to_i)
227       direction = format_direction((place.attributes["direction"].to_i - 180) % 360)
228       prefix = "#{distance} #{direction} of #{type} "
229       results.push({:lat => lat, :lon => lon, :zoom => zoom,
230                     :prefix => prefix.capitalize, :name => name,
231                     :description => description})
232     end
233
234     return { :type => types.capitalize, :source => "OpenStreetMap Namefinder", :url => "http://gazetteer.openstreetmap.org/namefinder/", :results => results }
235   rescue Exception => ex
236     return { :type => types.capitalize, :source => "OpenStreetMap Namefinder", :url => "http://gazetteer.openstreetmap.org/namefinder/", :error => "Error contacting gazetteer.openstreetmap.org: #{ex.to_s}" }
237   end
238
239   def description_geonames(lat, lon)
240     results = Array.new
241
242     # ask geonames.org
243     response = fetch_xml("http://ws.geonames.org/countrySubdivision?lat=#{lat}&lng=#{lon}")
244
245     # parse the response
246     response.elements.each("geonames/countrySubdivision") do |geoname|
247       name = geoname.get_text("adminName1").to_s
248       country = geoname.get_text("countryName").to_s
249       results.push({:prefix => "#{name}, #{country}"})
250     end
251
252     return { :type => "Location", :source => "GeoNames", :url => "http://www.geonames.org/", :results => results }
253   rescue Exception => ex
254     return { :type => "Location", :source => "GeoNames", :url => "http://www.geonames.org/", :error => "Error contacting ws.geonames.org: #{ex.to_s}" }
255   end
256
257   def fetch_text(url)
258     return Net::HTTP.get(URI.parse(url))
259   end
260
261   def fetch_xml(url)
262     return REXML::Document.new(fetch_text(url))
263   end
264
265   def format_distance(distance)
266     return "less than 1km" if distance == 0
267     return "about #{distance}km"
268   end
269
270   def format_direction(bearing)
271     return "south-west" if bearing >= 22.5 and bearing < 67.5
272     return "south" if bearing >= 67.5 and bearing < 112.5
273     return "south-east" if bearing >= 112.5 and bearing < 157.5
274     return "east" if bearing >= 157.5 and bearing < 202.5
275     return "north-east" if bearing >= 202.5 and bearing < 247.5
276     return "north" if bearing >= 247.5 and bearing < 292.5
277     return "north-west" if bearing >= 292.5 and bearing < 337.5
278     return "west"
279   end
280
281   def format_name(name)
282     return name.gsub(/( *\[[^\]]*\])*$/, "")
283   end
284
285   def count_results(results)
286     count = 0
287
288     results.each do |source|
289       count += source[:results].length if source[:results]
290     end
291
292     return count
293   end
294
295   def escape_query(query)
296     return URI.escape(query, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]", false, 'N'))
297   end
298 end