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