]> git.openstreetmap.org Git - rails.git/blob - app/controllers/geocoder_controller.rb
Redirect to the login page if auth failure has no origin
[rails.git] / app / controllers / geocoder_controller.rb
1 # coding: utf-8
2
3 class GeocoderController < ApplicationController
4   require "cgi"
5   require "uri"
6   require "rexml/document"
7
8   before_action :authorize_web
9   before_action :set_locale
10   before_action :require_oauth, :only => [:search]
11
12   def search
13     normalize_params
14
15     @sources = []
16     if params[:lat] && params[:lon]
17       @sources.push "latlon"
18       @sources.push "osm_nominatim_reverse"
19       @sources.push "geonames_reverse" if defined?(GEONAMES_USERNAME)
20     elsif params[:query].match(/^\d{5}(-\d{4})?$/)
21       @sources.push "us_postcode"
22       @sources.push "osm_nominatim"
23     elsif params[: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)
24       @sources.push "uk_postcode"
25       @sources.push "osm_nominatim"
26     elsif params[:query].match(/^[A-Z]\d[A-Z]\s*\d[A-Z]\d$/i)
27       @sources.push "ca_postcode"
28       @sources.push "osm_nominatim"
29     else
30       @sources.push "osm_nominatim"
31       @sources.push "geonames" if defined?(GEONAMES_USERNAME)
32     end
33
34     render :layout => map_layout
35   end
36
37   def search_latlon
38     lat = params[:lat].to_f
39     lon = params[:lon].to_f
40     if lat < -90 || lat > 90
41       @error = "Latitude #{lat} out of range"
42       render :action => "error"
43     elsif lon < -180 || lon > 180
44       @error = "Longitude #{lon} out of range"
45       render :action => "error"
46     else
47       @results = [{ :lat => lat, :lon => lon,
48                     :zoom => params[:zoom],
49                     :name => "#{lat}, #{lon}" }]
50
51       render :action => "results"
52     end
53   end
54
55   def search_us_postcode
56     # get query parameters
57     query = params[:query]
58
59     # create result array
60     @results = []
61
62     # ask geocoder.us (they have a non-commercial use api)
63     response = fetch_text("http://rpc.geocoder.us/service/csv?zip=#{escape_query(query)}")
64
65     # parse the response
66     unless response.match(/couldn't find this zip/)
67       data = response.split(/\s*,\s+/) # lat,long,town,state,zip
68       @results.push(:lat => data[0], :lon => data[1],
69                     :zoom => POSTCODE_ZOOM,
70                     :prefix => "#{data[2]}, #{data[3]},",
71                     :name => data[4])
72     end
73
74     render :action => "results"
75   rescue StandardError => ex
76     @error = "Error contacting rpc.geocoder.us: #{ex}"
77     render :action => "error"
78   end
79
80   def search_uk_postcode
81     # get query parameters
82     query = params[:query]
83
84     # create result array
85     @results = []
86
87     # ask npemap.org.uk to do a combined npemap + freethepostcode search
88     response = fetch_text("http://www.npemap.org.uk/cgi/geocoder.fcgi?format=text&postcode=#{escape_query(query)}")
89
90     # parse the response
91     unless response.match(/Error/)
92       dataline = response.split(/\n/)[1]
93       data = dataline.split(/,/) # easting,northing,postcode,lat,long
94       postcode = data[2].gsub(/'/, "")
95       zoom = POSTCODE_ZOOM - postcode.count("#")
96       @results.push(:lat => data[3], :lon => data[4], :zoom => zoom,
97                     :name => postcode)
98     end
99
100     render :action => "results"
101   rescue StandardError => ex
102     @error = "Error contacting www.npemap.org.uk: #{ex}"
103     render :action => "error"
104   end
105
106   def search_ca_postcode
107     # get query parameters
108     query = params[:query]
109     @results = []
110
111     # ask geocoder.ca (note - they have a per-day limit)
112     response = fetch_xml("http://geocoder.ca/?geoit=XML&postal=#{escape_query(query)}")
113
114     # parse the response
115     if response.get_elements("geodata/error").empty?
116       @results.push(:lat => response.get_text("geodata/latt").to_s,
117                     :lon => response.get_text("geodata/longt").to_s,
118                     :zoom => POSTCODE_ZOOM,
119                     :name => query.upcase)
120     end
121
122     render :action => "results"
123   rescue StandardError => ex
124     @error = "Error contacting geocoder.ca: #{ex}"
125     render :action => "error"
126   end
127
128   def search_osm_nominatim
129     # get query parameters
130     query = params[:query]
131     minlon = params[:minlon]
132     minlat = params[:minlat]
133     maxlon = params[:maxlon]
134     maxlat = params[:maxlat]
135
136     # get view box
137     if minlon && minlat && maxlon && maxlat
138       viewbox = "&viewbox=#{minlon},#{maxlat},#{maxlon},#{minlat}"
139     end
140
141     # get objects to excude
142     exclude = "&exclude_place_ids=#{params[:exclude]}" if params[:exclude]
143
144     # ask nominatim
145     response = fetch_xml("http:#{NOMINATIM_URL}search?format=xml&q=#{escape_query(query)}#{viewbox}#{exclude}&accept-language=#{http_accept_language.user_preferred_languages.join(',')}")
146
147     # extract the results from the response
148     results =  response.elements["searchresults"]
149
150     # extract parameters from more_url
151     more_url_params = CGI.parse(URI.parse(results.attributes["more_url"]).query)
152
153     # create result array
154     @results = []
155
156     # create parameter hash for "more results" link
157     @more_params = params.merge(:exclude => more_url_params["exclude_place_ids"].first)
158
159     # parse the response
160     results.elements.each("place") do |place|
161       lat = place.attributes["lat"].to_s
162       lon = place.attributes["lon"].to_s
163       klass = place.attributes["class"].to_s
164       type = place.attributes["type"].to_s
165       name = place.attributes["display_name"].to_s
166       min_lat, max_lat, min_lon, max_lon = place.attributes["boundingbox"].to_s.split(",")
167       if type.empty?
168         prefix_name = ""
169       else
170         prefix_name = t "geocoder.search_osm_nominatim.prefix.#{klass}.#{type}", :default => type.gsub("_", " ").capitalize
171       end
172       if klass == "boundary" && type == "administrative"
173         rank = (place.attributes["place_rank"].to_i + 1) / 2
174         prefix_name = t "geocoder.search_osm_nominatim.admin_levels.level#{rank}", :default => prefix_name
175       end
176       prefix = t "geocoder.search_osm_nominatim.prefix_format", :name => prefix_name
177       object_type = place.attributes["osm_type"]
178       object_id = place.attributes["osm_id"]
179
180       @results.push(:lat => lat, :lon => lon,
181                     :min_lat => min_lat, :max_lat => max_lat,
182                     :min_lon => min_lon, :max_lon => max_lon,
183                     :prefix => prefix, :name => name,
184                     :type => object_type, :id => object_id)
185     end
186
187     render :action => "results"
188   rescue StandardError => ex
189     @error = "Error contacting nominatim.openstreetmap.org: #{ex}"
190     render :action => "error"
191   end
192
193   def search_geonames
194     # get query parameters
195     query = params[:query]
196
197     # get preferred language
198     lang = I18n.locale.to_s.split("-").first
199
200     # create result array
201     @results = []
202
203     # ask geonames.org
204     response = fetch_xml("http://api.geonames.org/search?q=#{escape_query(query)}&lang=#{lang}&maxRows=20&username=#{GEONAMES_USERNAME}")
205
206     # parse the response
207     response.elements.each("geonames/geoname") do |geoname|
208       lat = geoname.get_text("lat").to_s
209       lon = geoname.get_text("lng").to_s
210       name = geoname.get_text("name").to_s
211       country = geoname.get_text("countryName").to_s
212       @results.push(:lat => lat, :lon => lon,
213                     :zoom => GEONAMES_ZOOM,
214                     :name => name,
215                     :suffix => ", #{country}")
216     end
217
218     render :action => "results"
219   rescue StandardError => ex
220     @error = "Error contacting api.geonames.org: #{ex}"
221     render :action => "error"
222   end
223
224   def search_osm_nominatim_reverse
225     # get query parameters
226     lat = params[:lat]
227     lon = params[:lon]
228     zoom = params[:zoom]
229
230     # create result array
231     @results = []
232
233     # ask nominatim
234     response = fetch_xml("http:#{NOMINATIM_URL}reverse?lat=#{lat}&lon=#{lon}&zoom=#{zoom}&accept-language=#{http_accept_language.user_preferred_languages.join(',')}")
235
236     # parse the response
237     response.elements.each("reversegeocode/result") do |result|
238       lat = result.attributes["lat"].to_s
239       lon = result.attributes["lon"].to_s
240       object_type = result.attributes["osm_type"]
241       object_id = result.attributes["osm_id"]
242       description = result.get_text.to_s
243
244       @results.push(:lat => lat, :lon => lon,
245                     :zoom => zoom,
246                     :name => description,
247                     :type => object_type, :id => object_id)
248     end
249
250     render :action => "results"
251   rescue StandardError => ex
252     @error = "Error contacting nominatim.openstreetmap.org: #{ex}"
253     render :action => "error"
254   end
255
256   def search_geonames_reverse
257     # get query parameters
258     lat = params[:lat]
259     lon = params[:lon]
260
261     # get preferred language
262     lang = I18n.locale.to_s.split("-").first
263
264     # create result array
265     @results = []
266
267     # ask geonames.org
268     response = fetch_xml("http://api.geonames.org/countrySubdivision?lat=#{lat}&lng=#{lon}&lang=#{lang}&username=#{GEONAMES_USERNAME}")
269
270     # parse the response
271     response.elements.each("geonames/countrySubdivision") do |geoname|
272       name = geoname.get_text("adminName1").to_s
273       country = geoname.get_text("countryName").to_s
274       @results.push(:lat => lat, :lon => lon,
275                     :zoom => GEONAMES_ZOOM,
276                     :name => name,
277                     :suffix => ", #{country}")
278     end
279
280     render :action => "results"
281   rescue StandardError => ex
282     @error = "Error contacting api.geonames.org: #{ex}"
283     render :action => "error"
284   end
285
286   private
287
288   def fetch_text(url)
289     OSM.http_client.get(URI.parse(url)).body
290   end
291
292   def fetch_xml(url)
293     REXML::Document.new(fetch_text(url))
294   end
295
296   def escape_query(query)
297     URI.escape(query, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]", false, "N"))
298   end
299
300   def normalize_params
301     query = params[:query]
302     return unless query
303
304     query.strip!
305
306     if latlon = query.match(/^([NS])\s*(\d{1,3}(\.\d*)?)\W*([EW])\s*(\d{1,3}(\.\d*)?)$/).try(:captures) # [NSEW] decimal degrees
307       params.merge!(nsew_to_decdeg(latlon)).delete(:query)
308     elsif latlon = query.match(/^(\d{1,3}(\.\d*)?)\s*([NS])\W*(\d{1,3}(\.\d*)?)\s*([EW])$/).try(:captures) # decimal degrees [NSEW]
309       params.merge!(nsew_to_decdeg(latlon)).delete(:query)
310
311     elsif latlon = query.match(/^([NS])\s*(\d{1,3})°?\s*(\d{1,3}(\.\d*)?)?['′]?\W*([EW])\s*(\d{1,3})°?\s*(\d{1,3}(\.\d*)?)?['′]?$/).try(:captures) # [NSEW] degrees, decimal minutes
312       params.merge!(ddm_to_decdeg(latlon)).delete(:query)
313     elsif latlon = query.match(/^(\d{1,3})°?\s*(\d{1,3}(\.\d*)?)?['′]?\s*([NS])\W*(\d{1,3})°?\s*(\d{1,3}(\.\d*)?)?['′]?\s*([EW])$/).try(:captures) # degrees, decimal minutes [NSEW]
314       params.merge!(ddm_to_decdeg(latlon)).delete(:query)
315
316     elsif latlon = query.match(/^([NS])\s*(\d{1,3})°?\s*(\d{1,2})['′]?\s*(\d{1,3}(\.\d*)?)?["″]?\W*([EW])\s*(\d{1,3})°?\s*(\d{1,2})['′]?\s*(\d{1,3}(\.\d*)?)?["″]?$/).try(:captures) # [NSEW] degrees, minutes, decimal seconds
317       params.merge!(dms_to_decdeg(latlon)).delete(:query)
318     elsif latlon = query.match(/^(\d{1,3})°?\s*(\d{1,2})['′]?\s*(\d{1,3}(\.\d*)?)?["″]\s*([NS])\W*(\d{1,3})°?\s*(\d{1,2})['′]?\s*(\d{1,3}(\.\d*)?)?["″]?\s*([EW])$/).try(:captures) # degrees, minutes, decimal seconds [NSEW]
319       params.merge!(dms_to_decdeg(latlon)).delete(:query)
320
321     elsif latlon = query.match(/^\s*([+-]?\d+(\.\d*)?)\s*[\s,]\s*([+-]?\d+(\.\d*)?)\s*$/)
322       params.merge!(:lat => latlon[1].to_f, :lon => latlon[3].to_f).delete(:query)
323     end
324   end
325
326   def nsew_to_decdeg(captures)
327     begin
328       Float(captures[0])
329       captures[2].downcase != "s" ? lat = captures[0].to_f : lat = -(captures[0].to_f)
330       captures[5].downcase != "w" ? lon = captures[3].to_f : lon = -(captures[3].to_f)
331     rescue
332       captures[0].downcase != "s" ? lat = captures[1].to_f : lat = -(captures[1].to_f)
333       captures[3].downcase != "w" ? lon = captures[4].to_f : lon = -(captures[4].to_f)
334     end
335     { :lat => lat, :lon => lon }
336   end
337
338   def ddm_to_decdeg(captures)
339     begin
340       Float(captures[0])
341       captures[3].downcase != "s" ? lat = captures[0].to_f + captures[1].to_f / 60 : lat = -(captures[0].to_f + captures[1].to_f / 60)
342       captures[7].downcase != "w" ? lon = captures[4].to_f + captures[5].to_f / 60 : lon = -(captures[4].to_f + captures[5].to_f / 60)
343     rescue
344       captures[0].downcase != "s" ? lat = captures[1].to_f + captures[2].to_f / 60 : lat = -(captures[1].to_f + captures[2].to_f / 60)
345       captures[4].downcase != "w" ? lon = captures[5].to_f + captures[6].to_f / 60 : lon = -(captures[5].to_f + captures[6].to_f / 60)
346     end
347     { :lat => lat, :lon => lon }
348   end
349
350   def dms_to_decdeg(captures)
351     begin
352       Float(captures[0])
353       captures[4].downcase != "s" ? lat = captures[0].to_f + (captures[1].to_f + captures[2].to_f / 60) / 60 : lat = -(captures[0].to_f + (captures[1].to_f + captures[2].to_f / 60) / 60)
354       captures[9].downcase != "w" ? lon = captures[5].to_f + (captures[6].to_f + captures[7].to_f / 60) / 60 : lon = -(captures[5].to_f + (captures[6].to_f + captures[7].to_f / 60) / 60)
355     rescue
356       captures[0].downcase != "s" ? lat = captures[1].to_f + (captures[2].to_f + captures[3].to_f / 60) / 60 : lat = -(captures[1].to_f + (captures[2].to_f + captures[3].to_f / 60) / 60)
357       captures[5].downcase != "w" ? lon = captures[6].to_f + (captures[7].to_f + captures[8].to_f / 60) / 60 : lon = -(captures[6].to_f + (captures[7].to_f + captures[8].to_f / 60) / 60)
358     end
359     { :lat => lat, :lon => lon }
360   end
361 end