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