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