]> git.openstreetmap.org Git - rails.git/blob - app/controllers/geocoder_controller.rb
Fixed merge fail - this branch doesn't have javascript_strings.
[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_namefinder"
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_namefinder"
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_geonames
217     # get query parameters
218     query = params[:query]
219
220     # create result array
221     @results = Array.new
222
223     # ask geonames.org
224     response = fetch_xml("http://ws.geonames.org/search?q=#{escape_query(query)}&maxRows=20")
225
226     # parse the response
227     response.elements.each("geonames/geoname") do |geoname|
228       lat = geoname.get_text("lat").to_s
229       lon = geoname.get_text("lng").to_s
230       name = geoname.get_text("name").to_s
231       country = geoname.get_text("countryName").to_s
232       @results.push({:lat => lat, :lon => lon,
233                      :zoom => APP_CONFIG['geonames_zoom'],
234                      :name => name,
235                      :suffix => ", #{country}"})
236     end
237
238     render :action => "results"
239   rescue Exception => ex
240     @error = "Error contacting ws.geonames.org: #{ex.to_s}"
241     render :action => "error"
242   end
243   
244   def description
245     @sources = Array.new
246
247     @sources.push({ :name => "osm_namefinder", :types => "cities", :max => 2 })
248     @sources.push({ :name => "osm_namefinder", :types => "towns", :max => 4 })
249     @sources.push({ :name => "osm_namefinder", :types => "places", :max => 10 })
250     @sources.push({ :name => "geonames" })
251
252     render :update do |page|
253       page.replace_html :sidebar_content, :partial => "description"
254       page.call "openSidebar"
255     end
256   end
257
258   def description_osm_namefinder
259     # get query parameters
260     lat = params[:lat]
261     lon = params[:lon]
262     types = params[:types]
263     max = params[:max]
264
265     # create result array
266     @results = Array.new
267
268     # ask OSM namefinder
269     response = fetch_xml("http://gazetteer.openstreetmap.org/namefinder/search.xml?find=#{types}+near+#{lat},#{lon}&max=#{max}")
270
271     # parse the response
272     response.elements.each("searchresults/named") do |named|
273       lat = named.attributes["lat"].to_s
274       lon = named.attributes["lon"].to_s
275       zoom = named.attributes["zoom"].to_s
276       place = named.elements["place/named"] || named.elements["nearestplaces/named"]
277       type = named.attributes["info"].to_s
278       name = named.attributes["name"].to_s
279       description = named.elements["description"].to_s
280       distance = format_distance(place.attributes["approxdistance"].to_i)
281       direction = format_direction((place.attributes["direction"].to_i - 180) % 360)
282       prefix = t "geocoder.description_osm_namefinder.prefix", :distance => distance, :direction => direction, :type => type
283       @results.push({:lat => lat, :lon => lon, :zoom => zoom,
284                      :prefix => prefix.capitalize, :name => name,
285                      :description => description})
286     end
287
288     render :action => "results"
289   rescue Exception => ex
290     @error = "Error contacting gazetteer.openstreetmap.org: #{ex.to_s}"
291     render :action => "error"
292   end
293
294   def description_geonames
295     # get query parameters
296     lat = params[:lat]
297     lon = params[:lon]
298
299     # create result array
300     @results = Array.new
301
302     # ask geonames.org
303     response = fetch_xml("http://ws.geonames.org/countrySubdivision?lat=#{lat}&lng=#{lon}")
304
305     # parse the response
306     response.elements.each("geonames/countrySubdivision") do |geoname|
307       name = geoname.get_text("adminName1").to_s
308       country = geoname.get_text("countryName").to_s
309       @results.push({:prefix => "#{name}, #{country}"})
310     end
311
312     render :action => "results"
313   rescue Exception => ex
314     @error = "Error contacting ws.geonames.org: #{ex.to_s}"
315     render :action => "error"
316   end
317
318 private
319
320   def fetch_text(url)
321     return Net::HTTP.get(URI.parse(url))
322   end
323
324   def fetch_xml(url)
325     return REXML::Document.new(fetch_text(url))
326   end
327
328   def format_distance(distance)
329     return t("geocoder.distance", :count => distance)
330   end
331
332   def format_direction(bearing)
333     return t("geocoder.direction.south_west") if bearing >= 22.5 and bearing < 67.5
334     return t("geocoder.direction.south") if bearing >= 67.5 and bearing < 112.5
335     return t("geocoder.direction.south_east") if bearing >= 112.5 and bearing < 157.5
336     return t("geocoder.direction.east") if bearing >= 157.5 and bearing < 202.5
337     return t("geocoder.direction.north_east") if bearing >= 202.5 and bearing < 247.5
338     return t("geocoder.direction.north") if bearing >= 247.5 and bearing < 292.5
339     return t("geocoder.direction.north_west") if bearing >= 292.5 and bearing < 337.5
340     return t("geocoder.direction.west")
341   end
342
343   def format_name(name)
344     return name.gsub(/( *\[[^\]]*\])*$/, "")
345   end
346
347   def count_results(results)
348     count = 0
349
350     results.each do |source|
351       count += source[:results].length if source[:results]
352     end
353
354     return count
355   end
356
357   def escape_query(query)
358     return URI.escape(query, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]", false, 'N'))
359   end
360 end