]> git.openstreetmap.org Git - rails.git/blob - app/controllers/geocoder_controller.rb
Fix a few nominatim issues.
[rails.git] / app / controllers / geocoder_controller.rb
1 class GeocoderController < ApplicationController
2   require 'uri'
3   require 'net/http'
4   require 'rexml/document'
5
6   before_filter :authorize_web
7   before_filter :set_locale
8
9   def search
10     @query = params[:query]
11     @sources = Array.new
12
13     @query.sub(/^\s+/, "")
14     @query.sub(/\s+$/, "")
15
16     if @query.match(/^[+-]?\d+(\.\d*)?\s*[\s,]\s*[+-]?\d+(\.\d*)?$/)
17       @sources.push "latlon"
18     elsif @query.match(/^\d{5}(-\d{4})?$/)
19       @sources.push "us_postcode"
20     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)
21       @sources.push "uk_postcode"
22       @sources.push "osm_nominatim" if APP_CONFIG['nominatim_enabled']
23       @sources.push "osm_namefinder"
24     elsif @query.match(/^[A-Z]\d[A-Z]\s*\d[A-Z]\d$/i)
25       @sources.push "ca_postcode"
26     else
27       @sources.push "osm_nominatim" if APP_CONFIG['nominatim_enabled']
28       @sources.push "osm_namefinder"
29       @sources.push "geonames"
30     end
31
32     render :update do |page|
33       page.replace_html :sidebar_content, :partial => "search"
34       page.call "openSidebar"
35     end
36   end
37
38   def search_latlon
39     # get query parameters
40     query = params[:query]
41
42     # create result array
43     @results = Array.new
44
45     # decode the location
46     if m = query.match(/^\s*([+-]?\d+(\.\d*)?)\s*[\s,]\s*([+-]?\d+(\.\d*)?)\s*$/)
47       lat = m[1].to_f
48       lon = m[3].to_f
49     end
50
51     # generate results
52     if lat < -90 or lat > 90
53       @error = "Latitude #{lat} out of range"
54       render :action => "error"
55     elsif lon < -180 or lon > 180
56       @error = "Longitude #{lon} out of range"
57       render :action => "error"
58     else
59       @results.push({:lat => lat, :lon => lon,
60                      :zoom => APP_CONFIG['postcode_zoom'],
61                      :name => "#{lat}, #{lon}"})
62
63       render :action => "results"
64     end
65   end
66
67   def search_us_postcode
68     # get query parameters
69     query = params[:query]
70
71     # create result array
72     @results = Array.new
73
74     # ask geocoder.us (they have a non-commercial use api)
75     response = fetch_text("http://rpc.geocoder.us/service/csv?zip=#{escape_query(query)}")
76
77     # parse the response
78     unless response.match(/couldn't find this zip/)
79       data = response.split(/\s*,\s+/) # lat,long,town,state,zip
80       @results.push({:lat => data[0], :lon => data[1],
81                      :zoom => APP_CONFIG['postcode_zoom'],
82                      :prefix => "#{data[2]}, #{data[3]},",
83                      :name => data[4]})
84     end
85
86     render :action => "results"
87   rescue Exception => ex
88     @error = "Error contacting rpc.geocoder.us: #{ex.to_s}"
89     render :action => "error"
90   end
91
92   def search_uk_postcode
93     # get query parameters
94     query = params[:query]
95
96     # create result array
97     @results = Array.new
98
99     # ask npemap.org.uk to do a combined npemap + freethepostcode search
100     response = fetch_text("http://www.npemap.org.uk/cgi/geocoder.fcgi?format=text&postcode=#{escape_query(query)}")
101
102     # parse the response
103     unless response.match(/Error/)
104       dataline = response.split(/\n/)[1]
105       data = dataline.split(/,/) # easting,northing,postcode,lat,long
106       postcode = data[2].gsub(/'/, "")
107       zoom = APP_CONFIG['postcode_zoom'] - postcode.count("#")
108       @results.push({:lat => data[3], :lon => data[4], :zoom => zoom,
109                      :name => postcode})
110     end
111
112     render :action => "results"
113   rescue Exception => ex
114     @error = "Error contacting www.npemap.org.uk: #{ex.to_s}"
115     render :action => "error"
116   end
117
118   def search_ca_postcode
119     # get query parameters
120     query = params[:query]
121     @results = Array.new
122
123     # ask geocoder.ca (note - they have a per-day limit)
124     response = fetch_xml("http://geocoder.ca/?geoit=XML&postal=#{escape_query(query)}")
125
126     # parse the response
127     if response.get_elements("geodata/error").empty?
128       @results.push({:lat => response.get_text("geodata/latt").to_s,
129                      :lon => response.get_text("geodata/longt").to_s,
130                      :zoom => APP_CONFIG['postcode_zoom'],
131                      :name => query.upcase})
132     end
133
134     render :action => "results"
135   rescue Exception => ex
136     @error = "Error contacting geocoder.ca: #{ex.to_s}"
137     render :action => "error"
138   end
139
140   def search_osm_namefinder
141     # get query parameters
142     query = params[:query]
143
144     # create result array
145     @results = Array.new
146
147     # ask OSM namefinder
148     response = fetch_xml("http://gazetteer.openstreetmap.org/namefinder/search.xml?find=#{escape_query(query)}")
149
150     # parse the response
151     response.elements.each("searchresults/named") do |named|
152       lat = named.attributes["lat"].to_s
153       lon = named.attributes["lon"].to_s
154       zoom = named.attributes["zoom"].to_s
155       place = named.elements["place/named"] || named.elements["nearestplaces/named"]
156       type = named.attributes["info"].to_s.capitalize
157       name = named.attributes["name"].to_s
158       description = named.elements["description"].to_s
159
160       if name.empty?
161         prefix = ""
162         name = type
163       else
164         prefix =  t "geocoder.search_osm_namefinder.prefix", :type => type
165       end
166
167       if place
168         distance = format_distance(place.attributes["approxdistance"].to_i)
169         direction = format_direction(place.attributes["direction"].to_i)
170         placename = format_name(place.attributes["name"].to_s)
171         suffix = t "geocoder.search_osm_namefinder.suffix_place", :distance => distance, :direction => direction, :placename => placename
172
173         if place.attributes["rank"].to_i <= 30
174           parent = nil
175           parentrank = 0
176           parentscore = 0
177
178           place.elements.each("nearestplaces/named") do |nearest|
179             nearestrank = nearest.attributes["rank"].to_i
180             nearestscore = nearestrank / nearest.attributes["distance"].to_f
181
182             if nearestrank > 30 and
183                ( nearestscore > parentscore or
184                  ( nearestscore == parentscore and nearestrank > parentrank ) )
185               parent = nearest
186               parentrank = nearestrank
187               parentscore = nearestscore
188             end
189           end
190
191           if parent
192             parentname = format_name(parent.attributes["name"].to_s)
193
194             if  place.attributes["info"].to_s == "suburb"
195               suffix = t "geocoder.search_osm_namefinder.suffix_suburb", :suffix => suffix, :parentname => parentname
196             else
197               parentdistance = format_distance(parent.attributes["approxdistance"].to_i)
198               parentdirection = format_direction(parent.attributes["direction"].to_i)
199               suffix = t "geocoder.search_osm_namefinder.suffix_parent", :suffix => suffix, :parentdistance => parentdistance, :parentdirection => parentdirection, :parentname => parentname
200             end
201           end
202         end
203       else
204         suffix = ""
205       end
206
207       @results.push({:lat => lat, :lon => lon, :zoom => zoom,
208                      :prefix => prefix, :name => name, :suffix => suffix,
209                      :description => description})
210     end
211
212     render :action => "results"
213   rescue Exception => ex
214     @error = "Error contacting gazetteer.openstreetmap.org: #{ex.to_s}"
215     render :action => "error"
216   end
217
218   def search_osm_nominatim
219     # get query parameters
220     query = params[:query]
221
222     # create result array
223     @results = Array.new
224
225     # ask OSM namefinder
226     response = fetch_xml("http://nominatim.openstreetmap.org/search?format=xml&q=#{escape_query(query)}")
227
228     # parse the response
229     response.elements.each("searchresults/place") do |place|
230       lat = place.attributes["lat"].to_s
231       lon = place.attributes["lon"].to_s
232       klass = place.attributes["class"].to_s
233       type = place.attributes["type"].to_s
234       name = place.attributes["display_name"].to_s
235       min_lat,max_lat,min_lon,max_lon = place.attributes["boundingbox"].to_s.split(",")
236
237       if klass == "highway"
238         prefix = t 'geocoder.search_osm_nominatim.prefix_highway', :type => type.capitalize
239       else
240         prefix = t 'geocoder.search_osm_nominatim.prefix_other', :type => type.capitalize
241       end
242
243       @results.push({:lat => lat, :lon => lon,
244                      :min_lat => min_lat, :max_lat => max_lat,
245                      :min_lon => min_lon, :max_lon => max_lon,
246                      :prefix => prefix, :name => name})
247     end
248
249     render :action => "results"
250   rescue Exception => ex
251     @error = "Error contacting nominatim.openstreetmap.org: #{ex.to_s}"
252     render :action => "error"
253   end
254
255   def search_geonames
256     # get query parameters
257     query = params[:query]
258
259     # create result array
260     @results = Array.new
261
262     # ask geonames.org
263     response = fetch_xml("http://ws.geonames.org/search?q=#{escape_query(query)}&maxRows=20")
264
265     # parse the response
266     response.elements.each("geonames/geoname") do |geoname|
267       lat = geoname.get_text("lat").to_s
268       lon = geoname.get_text("lng").to_s
269       name = geoname.get_text("name").to_s
270       country = geoname.get_text("countryName").to_s
271       @results.push({:lat => lat, :lon => lon,
272                      :zoom => APP_CONFIG['geonames_zoom'],
273                      :name => name,
274                      :suffix => ", #{country}"})
275     end
276
277     render :action => "results"
278   rescue Exception => ex
279     @error = "Error contacting ws.geonames.org: #{ex.to_s}"
280     render :action => "error"
281   end
282
283   def description
284     @sources = Array.new
285
286     @sources.push({ :name => "osm_nominatim" }) if APP_CONFIG['nominatim_enabled']
287     @sources.push({ :name => "osm_namefinder", :types => "cities", :max => 2 })
288     @sources.push({ :name => "osm_namefinder", :types => "towns", :max => 4 })
289     @sources.push({ :name => "osm_namefinder", :types => "places", :max => 10 })
290     @sources.push({ :name => "geonames" })
291
292     render :update do |page|
293       page.replace_html :sidebar_content, :partial => "description"
294       page.call "openSidebar"
295     end
296   end
297
298   def description_osm_namefinder
299     # get query parameters
300     lat = params[:lat]
301     lon = params[:lon]
302     types = params[:types]
303     max = params[:max]
304
305     # create result array
306     @results = Array.new
307
308     # ask OSM namefinder
309     response = fetch_xml("http://gazetteer.openstreetmap.org/namefinder/search.xml?find=#{types}+near+#{lat},#{lon}&max=#{max}")
310
311     # parse the response
312     response.elements.each("searchresults/named") do |named|
313       lat = named.attributes["lat"].to_s
314       lon = named.attributes["lon"].to_s
315       zoom = named.attributes["zoom"].to_s
316       place = named.elements["place/named"] || named.elements["nearestplaces/named"]
317       type = named.attributes["info"].to_s
318       name = named.attributes["name"].to_s
319       description = named.elements["description"].to_s
320       distance = format_distance(place.attributes["approxdistance"].to_i)
321       direction = format_direction((place.attributes["direction"].to_i - 180) % 360)
322       prefix = t "geocoder.description_osm_namefinder.prefix", :distance => distance, :direction => direction, :type => type
323       @results.push({:lat => lat, :lon => lon, :zoom => zoom,
324                      :prefix => prefix.capitalize, :name => name,
325                      :description => description})
326     end
327
328     render :action => "results"
329   rescue Exception => ex
330     @error = "Error contacting gazetteer.openstreetmap.org: #{ex.to_s}"
331     render :action => "error"
332   end
333
334   def description_osm_nominatim
335     # get query parameters
336     lat = params[:lat]
337     lon = params[:lon]
338     zoom = params[:zoom]
339
340     # create result array
341     @results = Array.new
342
343     # ask OSM namefinder
344     response = fetch_xml("http://nominatim.openstreetmap.org/reverse?lat=#{lat}&lon=#{lon}&zoom=#{zoom}")
345
346     # parse the response
347     response.elements.each("reversegeocode") do |result|
348       description = result.get_text("result").to_s
349
350       @results.push({:prefix => "#{description}"})
351     end
352
353     render :action => "results"
354   rescue Exception => ex
355     @error = "Error contacting nominatim.openstreetmap.org: #{ex.to_s}"
356     render :action => "error"
357   end
358
359   def description_geonames
360     # get query parameters
361     lat = params[:lat]
362     lon = params[:lon]
363
364     # create result array
365     @results = Array.new
366
367     # ask geonames.org
368     response = fetch_xml("http://ws.geonames.org/countrySubdivision?lat=#{lat}&lng=#{lon}")
369
370     # parse the response
371     response.elements.each("geonames/countrySubdivision") do |geoname|
372       name = geoname.get_text("adminName1").to_s
373       country = geoname.get_text("countryName").to_s
374       @results.push({:prefix => "#{name}, #{country}"})
375     end
376
377     render :action => "results"
378   rescue Exception => ex
379     @error = "Error contacting ws.geonames.org: #{ex.to_s}"
380     render :action => "error"
381   end
382
383 private
384
385   def fetch_text(url)
386     return Net::HTTP.get(URI.parse(url))
387   end
388
389   def fetch_xml(url)
390     return REXML::Document.new(fetch_text(url))
391   end
392
393   def format_distance(distance)
394     return t("geocoder.distance", :count => distance)
395   end
396
397   def format_direction(bearing)
398     return t("geocoder.direction.south_west") if bearing >= 22.5 and bearing < 67.5
399     return t("geocoder.direction.south") if bearing >= 67.5 and bearing < 112.5
400     return t("geocoder.direction.south_east") if bearing >= 112.5 and bearing < 157.5
401     return t("geocoder.direction.east") if bearing >= 157.5 and bearing < 202.5
402     return t("geocoder.direction.north_east") if bearing >= 202.5 and bearing < 247.5
403     return t("geocoder.direction.north") if bearing >= 247.5 and bearing < 292.5
404     return t("geocoder.direction.north_west") if bearing >= 292.5 and bearing < 337.5
405     return t("geocoder.direction.west")
406   end
407
408   def format_name(name)
409     return name.gsub(/( *\[[^\]]*\])*$/, "")
410   end
411
412   def count_results(results)
413     count = 0
414
415     results.each do |source|
416       count += source[:results].length if source[:results]
417     end
418
419     return count
420   end
421
422   def escape_query(query)
423     return URI.escape(query, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]", false, 'N'))
424   end
425 end