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