]> git.openstreetmap.org Git - rails.git/blob - app/controllers/geocoder_controller.rb
Merge remote-tracking branch 'upstream/pull/1704'
[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 "uk_postcode"
23         @sources.push "osm_nominatim"
24       elsif @params[:query] =~ /^[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 defined?(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     if lat < -90 || lat > 90
44       @error = "Latitude #{lat} out of range"
45       render :action => "error"
46     elsif lon < -180 || lon > 180
47       @error = "Longitude #{lon} out of range"
48       render :action => "error"
49     else
50       @results = [{ :lat => lat, :lon => lon,
51                     :zoom => params[:zoom],
52                     :name => "#{lat}, #{lon}" }]
53
54       render :action => "results"
55     end
56   end
57
58   def search_uk_postcode
59     # get query parameters
60     query = params[:query]
61
62     # create result array
63     @results = []
64
65     # ask npemap.org.uk to do a combined npemap + freethepostcode search
66     response = fetch_text("http://www.npemap.org.uk/cgi/geocoder.fcgi?format=text&postcode=#{escape_query(query)}")
67
68     # parse the response
69     unless response =~ /Error/
70       dataline = response.split(/\n/)[1]
71       data = dataline.split(/,/) # easting,northing,postcode,lat,long
72       postcode = data[2].delete("'")
73       zoom = POSTCODE_ZOOM - postcode.count("#")
74       @results.push(:lat => data[3], :lon => data[4], :zoom => zoom,
75                     :name => postcode)
76     end
77
78     render :action => "results"
79   rescue StandardError => ex
80     @error = "Error contacting www.npemap.org.uk: #{ex}"
81     render :action => "error"
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 => POSTCODE_ZOOM,
97                     :name => query.upcase)
98     end
99
100     render :action => "results"
101   rescue StandardError => ex
102     @error = "Error contacting geocoder.ca: #{ex}"
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("#{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["place_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"] == "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 => ex
170     @error = "Error contacting nominatim.openstreetmap.org: #{ex}"
171     render :action => "error"
172   end
173
174   def search_geonames
175     # get query parameters
176     query = params[:query]
177
178     # get preferred language
179     lang = I18n.locale.to_s.split("-").first
180
181     # create result array
182     @results = []
183
184     # ask geonames.org
185     response = fetch_xml("http://api.geonames.org/search?q=#{escape_query(query)}&lang=#{lang}&maxRows=20&username=#{GEONAMES_USERNAME}")
186
187     # parse the response
188     response.elements.each("geonames/geoname") do |geoname|
189       lat = geoname.text("lat")
190       lon = geoname.text("lng")
191       name = geoname.text("name")
192       country = geoname.text("countryName")
193
194       @results.push(:lat => lat, :lon => lon,
195                     :zoom => GEONAMES_ZOOM,
196                     :name => name,
197                     :suffix => ", #{country}")
198     end
199
200     render :action => "results"
201   rescue StandardError => ex
202     @error = "Error contacting api.geonames.org: #{ex}"
203     render :action => "error"
204   end
205
206   def search_osm_nominatim_reverse
207     # get query parameters
208     lat = params[:lat]
209     lon = params[:lon]
210     zoom = params[:zoom]
211
212     # create result array
213     @results = []
214
215     # ask nominatim
216     response = fetch_xml("#{NOMINATIM_URL}reverse?lat=#{lat}&lon=#{lon}&zoom=#{zoom}&accept-language=#{http_accept_language.user_preferred_languages.join(',')}")
217
218     # parse the response
219     response.elements.each("reversegeocode/result") do |result|
220       lat = result.attributes["lat"]
221       lon = result.attributes["lon"]
222       object_type = result.attributes["osm_type"]
223       object_id = result.attributes["osm_id"]
224       description = result.text
225
226       @results.push(:lat => lat, :lon => lon,
227                     :zoom => zoom,
228                     :name => description,
229                     :type => object_type, :id => object_id)
230     end
231
232     render :action => "results"
233   rescue StandardError => ex
234     @error = "Error contacting nominatim.openstreetmap.org: #{ex}"
235     render :action => "error"
236   end
237
238   def search_geonames_reverse
239     # get query parameters
240     lat = params[:lat]
241     lon = params[:lon]
242
243     # get preferred language
244     lang = I18n.locale.to_s.split("-").first
245
246     # create result array
247     @results = []
248
249     # ask geonames.org
250     response = fetch_xml("http://api.geonames.org/countrySubdivision?lat=#{lat}&lng=#{lon}&lang=#{lang}&username=#{GEONAMES_USERNAME}")
251
252     # parse the response
253     response.elements.each("geonames/countrySubdivision") do |geoname|
254       name = geoname.text("adminName1")
255       country = geoname.text("countryName")
256
257       @results.push(:lat => lat, :lon => lon,
258                     :zoom => GEONAMES_ZOOM,
259                     :name => name,
260                     :suffix => ", #{country}")
261     end
262
263     render :action => "results"
264   rescue StandardError => ex
265     @error = "Error contacting api.geonames.org: #{ex}"
266     render :action => "error"
267   end
268
269   private
270
271   def fetch_text(url)
272     response = OSM.http_client.get(URI.parse(url))
273
274     if response.success?
275       response.body
276     else
277       raise response.status.to_s
278     end
279   end
280
281   def fetch_xml(url)
282     REXML::Document.new(fetch_text(url))
283   end
284
285   def escape_query(query)
286     CGI.escape(query)
287   end
288
289   def normalize_params
290     if query = params[:query]
291       query.strip!
292
293       if latlon = query.match(/^([NS])\s*(\d{1,3}(\.\d*)?)\W*([EW])\s*(\d{1,3}(\.\d*)?)$/).try(:captures) # [NSEW] decimal degrees
294         params.merge!(nsew_to_decdeg(latlon)).delete(:query)
295       elsif latlon = query.match(/^(\d{1,3}(\.\d*)?)\s*([NS])\W*(\d{1,3}(\.\d*)?)\s*([EW])$/).try(:captures) # decimal degrees [NSEW]
296         params.merge!(nsew_to_decdeg(latlon)).delete(:query)
297
298       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
299         params.merge!(ddm_to_decdeg(latlon)).delete(:query)
300       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]
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         params.merge!(dms_to_decdeg(latlon)).delete(:query)
305       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]
306         params.merge!(dms_to_decdeg(latlon)).delete(:query)
307
308       elsif latlon = query.match(/^\s*([+-]?\d+(\.\d*)?)\s*[\s,]\s*([+-]?\d+(\.\d*)?)\s*$/)
309         params.merge!(:lat => latlon[1].to_f, :lon => latlon[3].to_f).delete(:query)
310       end
311     end
312
313     params.permit(:query, :lat, :lon, :zoom, :minlat, :minlon, :maxlat, :maxlon)
314   end
315
316   def nsew_to_decdeg(captures)
317     begin
318       Float(captures[0])
319       lat = !captures[2].casecmp("s").zero? ? captures[0].to_f : -captures[0].to_f
320       lon = !captures[5].casecmp("w").zero? ? captures[3].to_f : -captures[3].to_f
321     rescue StandardError
322       lat = !captures[0].casecmp("s").zero? ? captures[1].to_f : -captures[1].to_f
323       lon = !captures[3].casecmp("w").zero? ? captures[4].to_f : -captures[4].to_f
324     end
325     { :lat => lat, :lon => lon }
326   end
327
328   def ddm_to_decdeg(captures)
329     begin
330       Float(captures[0])
331       lat = !captures[3].casecmp("s").zero? ? captures[0].to_f + captures[1].to_f / 60 : -(captures[0].to_f + captures[1].to_f / 60)
332       lon = !captures[7].casecmp("w").zero? ? captures[4].to_f + captures[5].to_f / 60 : -(captures[4].to_f + captures[5].to_f / 60)
333     rescue StandardError
334       lat = !captures[0].casecmp("s").zero? ? captures[1].to_f + captures[2].to_f / 60 : -(captures[1].to_f + captures[2].to_f / 60)
335       lon = !captures[4].casecmp("w").zero? ? captures[5].to_f + captures[6].to_f / 60 : -(captures[5].to_f + captures[6].to_f / 60)
336     end
337     { :lat => lat, :lon => lon }
338   end
339
340   def dms_to_decdeg(captures)
341     begin
342       Float(captures[0])
343       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)
344       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)
345     rescue StandardError
346       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)
347       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)
348     end
349     { :lat => lat, :lon => lon }
350   end
351 end