]> git.openstreetmap.org Git - rails.git/blob - app/controllers/geocoder_controller.rb
Merge remote-tracking branch 'upstream/pull/5923'
[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   authorize_resource :class => false
11
12   before_action :normalize_params, :only => [:search]
13
14   def search
15     @sources = []
16
17     if params[:lat] && params[:lon]
18       @sources.push(:name => "latlon", :url => root_path,
19                     :fetch_url => url_for(params.permit(:lat, :lon, :latlon_digits, :zoom).merge(:action => "search_latlon")))
20       @sources.push(:name => "osm_nominatim_reverse", :url => nominatim_reverse_url(:format => "html"),
21                     :fetch_url => url_for(params.permit(:lat, :lon, :zoom).merge(:action => "search_osm_nominatim_reverse")))
22     elsif params[:query]
23       @sources.push(:name => "osm_nominatim", :url => nominatim_url(:format => "html"),
24                     :fetch_url => url_for(params.permit(:query, :minlat, :minlon, :maxlat, :maxlon).merge(:action => "search_osm_nominatim")))
25     end
26
27     if @sources.empty?
28       head :bad_request
29     else
30       render :layout => map_layout
31     end
32   end
33
34   def search_latlon
35     lat = params[:lat].to_f
36     lon = params[:lon].to_f
37
38     if params[:latlon_digits]
39       # We've got two nondescript numbers for a query, which can mean both "lat, lon" or "lon, lat".
40       @results = []
41
42       if lat.between?(-90, 90) && lon.between?(-180, 180)
43         @results.push(:lat => params[:lat], :lon => params[:lon],
44                       :zoom => params[:zoom],
45                       :name => "#{params[:lat]}, #{params[:lon]}")
46       end
47
48       if lon.between?(-90, 90) && lat.between?(-180, 180)
49         @results.push(:lat => params[:lon], :lon => params[:lat],
50                       :zoom => params[:zoom],
51                       :name => "#{params[:lon]}, #{params[:lat]}")
52       end
53
54       if @results.empty?
55         @error = "Latitude or longitude are out of range"
56         render :action => "error"
57       else
58         render :action => "results"
59       end
60     else
61       # Coordinates in a query have come with markers for latitude and longitude.
62       if !lat.between?(-90, 90)
63         @error = "Latitude #{lat} out of range"
64         render :action => "error"
65       elsif !lon.between?(-180, 180)
66         @error = "Longitude #{lon} out of range"
67         render :action => "error"
68       else
69         @results = [{ :lat => params[:lat], :lon => params[:lon],
70                       :zoom => params[:zoom],
71                       :name => "#{params[:lat]}, #{params[:lon]}" }]
72
73         render :action => "results"
74       end
75     end
76   end
77
78   def search_osm_nominatim
79     # ask nominatim
80     response = fetch_xml(nominatim_url(:format => "xml"))
81
82     # extract the results from the response
83     results = response.elements["searchresults"]
84
85     # create result array
86     @results = []
87
88     # create parameter hash for "more results" link
89     @more_params = params
90                    .permit(:query, :minlon, :minlat, :maxlon, :maxlat, :exclude)
91                    .merge(:exclude => results.attributes["exclude_place_ids"])
92
93     # parse the response
94     results.elements.each("place") do |place|
95       lat = place.attributes["lat"]
96       lon = place.attributes["lon"]
97       klass = place.attributes["class"]
98       type = place.attributes["type"]
99       name = place.attributes["display_name"]
100       min_lat, max_lat, min_lon, max_lon = place.attributes["boundingbox"].split(",")
101       prefix_name = if type.empty?
102                       ""
103                     else
104                       t "geocoder.search_osm_nominatim.prefix.#{klass}.#{type}", :default => type.tr("_", " ").capitalize
105                     end
106       if klass == "boundary" && type == "administrative"
107         rank = (place.attributes["address_rank"].to_i + 1) / 2
108         prefix_name = t "geocoder.search_osm_nominatim.admin_levels.level#{rank}", :default => prefix_name
109         border_type = nil
110         place_type = nil
111         place_tags = %w[linked_place place]
112         place.elements["extratags"].elements.each("tag") do |extratag|
113           border_type = t "geocoder.search_osm_nominatim.border_types.#{extratag.attributes['value']}", :default => border_type if extratag.attributes["key"] == "border_type"
114           place_type = t "geocoder.search_osm_nominatim.prefix.place.#{extratag.attributes['value']}", :default => place_type if place_tags.include?(extratag.attributes["key"])
115         end
116         prefix_name = place_type || border_type || prefix_name
117       end
118       prefix = t ".prefix_format", :name => prefix_name
119       object_type = place.attributes["osm_type"]
120       object_id = place.attributes["osm_id"]
121
122       @results.push(:lat => lat, :lon => lon,
123                     :min_lat => min_lat, :max_lat => max_lat,
124                     :min_lon => min_lon, :max_lon => max_lon,
125                     :prefix => prefix, :name => name,
126                     :type => object_type, :id => object_id)
127     end
128
129     render :action => "results"
130   rescue StandardError => e
131     host = URI(Settings.nominatim_url).host
132     @error = "Error contacting #{host}: #{e}"
133     render :action => "error"
134   end
135
136   def search_osm_nominatim_reverse
137     # get query parameters
138     zoom = params[:zoom]
139
140     # create result array
141     @results = []
142
143     # ask nominatim
144     response = fetch_xml(nominatim_reverse_url(:format => "xml"))
145
146     # parse the response
147     response.elements.each("reversegeocode/result") do |result|
148       lat = result.attributes["lat"]
149       lon = result.attributes["lon"]
150       object_type = result.attributes["osm_type"]
151       object_id = result.attributes["osm_id"]
152       description = result.text
153
154       @results.push(:lat => lat, :lon => lon,
155                     :zoom => zoom,
156                     :name => description,
157                     :type => object_type, :id => object_id)
158     end
159
160     render :action => "results"
161   rescue StandardError => e
162     host = URI(Settings.nominatim_url).host
163     @error = "Error contacting #{host}: #{e}"
164     render :action => "error"
165   end
166
167   private
168
169   def nominatim_url(format: nil)
170     # get query parameters
171     query = params[:query]
172     minlon = params[:minlon]
173     minlat = params[:minlat]
174     maxlon = params[:maxlon]
175     maxlat = params[:maxlat]
176
177     # get view box
178     viewbox = "&viewbox=#{minlon},#{maxlat},#{maxlon},#{minlat}" if minlon && minlat && maxlon && maxlat
179
180     # get objects to excude
181     exclude = "&exclude_place_ids=#{params[:exclude]}" if params[:exclude]
182
183     # build url
184     "#{Settings.nominatim_url}search?format=#{format}&extratags=1&q=#{escape_query(query)}#{viewbox}#{exclude}&accept-language=#{http_accept_language.user_preferred_languages.join(',')}"
185   end
186
187   def nominatim_reverse_url(format: nil)
188     # get query parameters
189     lat = params[:lat]
190     lon = params[:lon]
191     zoom = params[:zoom]
192
193     # build url
194     "#{Settings.nominatim_url}reverse?format=#{format}&lat=#{lat}&lon=#{lon}&zoom=#{zoom}&accept-language=#{http_accept_language.user_preferred_languages.join(',')}"
195   end
196
197   def fetch_text(url)
198     response = OSM.http_client.get(URI.parse(url))
199
200     if response.success?
201       response.body
202     else
203       raise response.status.to_s
204     end
205   end
206
207   def fetch_xml(url)
208     REXML::Document.new(fetch_text(url))
209   end
210
211   def escape_query(query)
212     CGI.escape(query)
213   end
214
215   def normalize_params
216     if query = params[:query]
217       query.strip!
218
219       if latlon = query.match(/^(?<ns>[NS])\s*#{dms_regexp('ns')}\W*(?<ew>[EW])\s*#{dms_regexp('ew')}$/) ||
220                   query.match(/^#{dms_regexp('ns')}\s*(?<ns>[NS])\W*#{dms_regexp('ew')}\s*(?<ew>[EW])$/)
221         params.merge!(to_decdeg(latlon.named_captures.compact)).delete(:query)
222
223       elsif latlon = query.match(%r{^(?<lat>[+-]?\d+(?:\.\d+)?)(?:\s+|\s*[,/]\s*)(?<lon>[+-]?\d+(?:\.\d+)?)$})
224         params.merge!(:lat => latlon["lat"], :lon => latlon["lon"]).delete(:query)
225
226         params[:latlon_digits] = true
227       end
228     end
229   end
230
231   def dms_regexp(name_prefix)
232     /
233       (?: (?<#{name_prefix}d>\d{1,3}(?:\.\d+)?)°? ) |
234       (?: (?<#{name_prefix}d>\d{1,3})°?\s*(?<#{name_prefix}m>\d{1,2}(?:\.\d+)?)['′]? ) |
235       (?: (?<#{name_prefix}d>\d{1,3})°?\s*(?<#{name_prefix}m>\d{1,2})['′]?\s*(?<#{name_prefix}s>\d{1,2}(?:\.\d+)?)["″]? )
236     /x
237   end
238
239   def to_decdeg(captures)
240     ns = captures.fetch("ns").casecmp?("s") ? -1 : 1
241     nsd = BigDecimal(captures.fetch("nsd", "0"))
242     nsm = BigDecimal(captures.fetch("nsm", "0"))
243     nss = BigDecimal(captures.fetch("nss", "0"))
244
245     ew = captures.fetch("ew").casecmp?("w") ? -1 : 1
246     ewd = BigDecimal(captures.fetch("ewd", "0"))
247     ewm = BigDecimal(captures.fetch("ewm", "0"))
248     ews = BigDecimal(captures.fetch("ews", "0"))
249
250     lat = ns * (nsd + (nsm / 60) + (nss / 3600))
251     lon = ew * (ewd + (ewm / 60) + (ews / 3600))
252
253     { :lat => lat.round(6).to_s("F"), :lon => lon.round(6).to_s("F") }
254   end
255 end