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