]> git.openstreetmap.org Git - rails.git/blob - app/controllers/geocoder_controller.rb
Move nominatim url methods to concerns
[rails.git] / app / controllers / geocoder_controller.rb
1 class GeocoderController < ApplicationController
2   require "uri"
3   require "rexml/document"
4   include NominatimMethods
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_query_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_query_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_query_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_query_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 fetch_text(url)
170     response = OSM.http_client.get(URI.parse(url))
171
172     if response.success?
173       response.body
174     else
175       raise response.status.to_s
176     end
177   end
178
179   def fetch_xml(url)
180     REXML::Document.new(fetch_text(url))
181   end
182
183   def normalize_params
184     if (query = params[:query])
185       query.strip!
186
187       if (latlon = query.match(/^(?<ns>[NS])\s*#{dms_regexp('ns')}\W*(?<ew>[EW])\s*#{dms_regexp('ew')}$/) ||
188                    query.match(/^#{dms_regexp('ns')}\s*(?<ns>[NS])\W*#{dms_regexp('ew')}\s*(?<ew>[EW])$/))
189         params.merge!(to_decdeg(latlon.named_captures.compact)).delete(:query)
190
191       elsif (latlon = query.match(%r{^(?<lat>[+-]?\d+(?:\.\d+)?)(?:\s+|\s*[,/]\s*)(?<lon>[+-]?\d+(?:\.\d+)?)$}))
192         params.merge!(latlon.named_captures).delete(:query)
193
194         params[:latlon_digits] = true
195       end
196     end
197   end
198
199   def dms_regexp(name_prefix)
200     /
201       (?: (?<#{name_prefix}d>\d{1,3}(?:\.\d+)?)°? ) |
202       (?: (?<#{name_prefix}d>\d{1,3})°?\s*(?<#{name_prefix}m>\d{1,2}(?:\.\d+)?)['′]? ) |
203       (?: (?<#{name_prefix}d>\d{1,3})°?\s*(?<#{name_prefix}m>\d{1,2})['′]?\s*(?<#{name_prefix}s>\d{1,2}(?:\.\d+)?)["″]? )
204     /x
205   end
206
207   def to_decdeg(captures)
208     ns = captures.fetch("ns").casecmp?("s") ? -1 : 1
209     nsd = BigDecimal(captures.fetch("nsd", "0"))
210     nsm = BigDecimal(captures.fetch("nsm", "0"))
211     nss = BigDecimal(captures.fetch("nss", "0"))
212
213     ew = captures.fetch("ew").casecmp?("w") ? -1 : 1
214     ewd = BigDecimal(captures.fetch("ewd", "0"))
215     ewm = BigDecimal(captures.fetch("ewm", "0"))
216     ews = BigDecimal(captures.fetch("ews", "0"))
217
218     lat = ns * (nsd + (nsm / 60) + (nss / 3600))
219     lon = ew * (ewd + (ewm / 60) + (ews / 3600))
220
221     { :lat => lat.round(6).to_s("F"), :lon => lon.round(6).to_s("F") }
222   end
223 end