1 class GeocoderController < ApplicationController
4 require "rexml/document"
6 before_action :authorize_web
7 before_action :set_locale
8 before_action :require_oauth, :only => [:search]
9 authorize_resource :class => false
12 @params = normalize_params
15 if @params[:lat] && @params[:lon]
16 @sources.push "latlon"
17 @sources.push "osm_nominatim_reverse"
19 @sources.push "osm_nominatim"
25 render :layout => map_layout
30 lat = params[:lat].to_f
31 lon = params[:lon].to_f
33 if params[:latlon_digits]
34 # We've got two nondescript numbers for a query, which can mean both "lat, lon" or "lon, lat".
37 if lat >= -90 && lat <= 90 && lon >= -180 && lon <= 180
38 @results.push(:lat => lat, :lon => lon,
39 :zoom => params[:zoom],
40 :name => "#{lat}, #{lon}")
43 if lon >= -90 && lon <= 90 && lat >= -180 && lat <= 180
44 @results.push(:lat => lon, :lon => lat,
45 :zoom => params[:zoom],
46 :name => "#{lon}, #{lat}")
50 @error = "Latitude or longitude are out of range"
51 render :action => "error"
53 render :action => "results"
56 # Coordinates in a query have come with markers for latitude and longitude.
57 if lat < -90 || lat > 90
58 @error = "Latitude #{lat} out of range"
59 render :action => "error"
60 elsif lon < -180 || lon > 180
61 @error = "Longitude #{lon} out of range"
62 render :action => "error"
64 @results = [{ :lat => lat, :lon => lon,
65 :zoom => params[:zoom],
66 :name => "#{lat}, #{lon}" }]
68 render :action => "results"
73 def search_osm_nominatim
74 # get query parameters
75 query = params[:query]
76 minlon = params[:minlon]
77 minlat = params[:minlat]
78 maxlon = params[:maxlon]
79 maxlat = params[:maxlat]
82 viewbox = "&viewbox=#{minlon},#{maxlat},#{maxlon},#{minlat}" if minlon && minlat && maxlon && maxlat
84 # get objects to excude
85 exclude = "&exclude_place_ids=#{params[:exclude]}" if params[:exclude]
88 response = fetch_xml("#{Settings.nominatim_url}search?format=xml&extratags=1&q=#{escape_query(query)}#{viewbox}#{exclude}&accept-language=#{http_accept_language.user_preferred_languages.join(',')}")
90 # extract the results from the response
91 results = response.elements["searchresults"]
93 # extract parameters from more_url
94 more_url_params = CGI.parse(URI.parse(results.attributes["more_url"]).query)
99 # create parameter hash for "more results" link
100 @more_params = params
101 .permit(:query, :minlon, :minlat, :maxlon, :maxlat, :exclude)
102 .merge(:exclude => more_url_params["exclude_place_ids"].first)
105 results.elements.each("place") do |place|
106 lat = place.attributes["lat"]
107 lon = place.attributes["lon"]
108 klass = place.attributes["class"]
109 type = place.attributes["type"]
110 name = place.attributes["display_name"]
111 min_lat, max_lat, min_lon, max_lon = place.attributes["boundingbox"].split(",")
112 prefix_name = if type.empty?
115 t "geocoder.search_osm_nominatim.prefix.#{klass}.#{type}", :default => type.tr("_", " ").capitalize
117 if klass == "boundary" && type == "administrative"
118 rank = (place.attributes["address_rank"].to_i + 1) / 2
119 prefix_name = t "geocoder.search_osm_nominatim.admin_levels.level#{rank}", :default => prefix_name
120 place.elements["extratags"].elements.each("tag") do |extratag|
121 prefix_name = t "geocoder.search_osm_nominatim.prefix.place.#{extratag.attributes['value']}", :default => prefix_name if extratag.attributes["key"] == "linked_place" || extratag.attributes["key"] == "place"
124 prefix = t ".prefix_format", :name => prefix_name
125 object_type = place.attributes["osm_type"]
126 object_id = place.attributes["osm_id"]
128 @results.push(:lat => lat, :lon => lon,
129 :min_lat => min_lat, :max_lat => max_lat,
130 :min_lon => min_lon, :max_lon => max_lon,
131 :prefix => prefix, :name => name,
132 :type => object_type, :id => object_id)
135 render :action => "results"
136 rescue StandardError => e
137 host = URI(Settings.nominatim_url).host
138 @error = "Error contacting #{host}: #{e}"
139 render :action => "error"
142 def search_osm_nominatim_reverse
143 # get query parameters
148 # create result array
152 response = fetch_xml("#{Settings.nominatim_url}reverse?lat=#{lat}&lon=#{lon}&zoom=#{zoom}&accept-language=#{http_accept_language.user_preferred_languages.join(',')}")
155 response.elements.each("reversegeocode/result") do |result|
156 lat = result.attributes["lat"]
157 lon = result.attributes["lon"]
158 object_type = result.attributes["osm_type"]
159 object_id = result.attributes["osm_id"]
160 description = result.text
162 @results.push(:lat => lat, :lon => lon,
164 :name => description,
165 :type => object_type, :id => object_id)
168 render :action => "results"
169 rescue StandardError => e
170 host = URI(Settings.nominatim_url).host
171 @error = "Error contacting #{host}: #{e}"
172 render :action => "error"
178 response = OSM.http_client.get(URI.parse(url))
183 raise response.status.to_s
188 REXML::Document.new(fetch_text(url))
191 def escape_query(query)
196 if query = params[:query]
199 if latlon = query.match(/^([NS])\s*(\d{1,3}(\.\d*)?)\W*([EW])\s*(\d{1,3}(\.\d*)?)$/).try(:captures) || # [NSEW] decimal degrees
200 query.match(/^(\d{1,3}(\.\d*)?)\s*([NS])\W*(\d{1,3}(\.\d*)?)\s*([EW])$/).try(:captures) # decimal degrees [NSEW]
201 params.merge!(nsew_to_decdeg(latlon)).delete(:query)
203 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
204 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]
205 params.merge!(ddm_to_decdeg(latlon)).delete(:query)
207 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
208 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]
209 params.merge!(dms_to_decdeg(latlon)).delete(:query)
211 elsif latlon = query.match(/^([+-]?\d+(\.\d*)?)(?:\s+|\s*,\s*)([+-]?\d+(\.\d*)?)$/)
212 params.merge!(:lat => latlon[1].to_f, :lon => latlon[3].to_f).delete(:query)
214 params[:latlon_digits] = true unless params[:whereami]
218 params.permit(:query, :lat, :lon, :latlon_digits, :zoom, :minlat, :minlon, :maxlat, :maxlon)
221 def nsew_to_decdeg(captures)
224 lat = captures[2].casecmp("s").zero? ? -captures[0].to_f : captures[0].to_f
225 lon = captures[5].casecmp("w").zero? ? -captures[3].to_f : captures[3].to_f
227 lat = captures[0].casecmp("s").zero? ? -captures[1].to_f : captures[1].to_f
228 lon = captures[3].casecmp("w").zero? ? -captures[4].to_f : captures[4].to_f
230 { :lat => lat, :lon => lon }
233 def ddm_to_decdeg(captures)
236 lat = captures[3].casecmp("s").zero? ? -(captures[0].to_f + (captures[1].to_f / 60)) : captures[0].to_f + (captures[1].to_f / 60)
237 lon = captures[7].casecmp("w").zero? ? -(captures[4].to_f + (captures[5].to_f / 60)) : captures[4].to_f + (captures[5].to_f / 60)
239 lat = captures[0].casecmp("s").zero? ? -(captures[1].to_f + (captures[2].to_f / 60)) : captures[1].to_f + (captures[2].to_f / 60)
240 lon = captures[4].casecmp("w").zero? ? -(captures[5].to_f + (captures[6].to_f / 60)) : captures[5].to_f + (captures[6].to_f / 60)
242 { :lat => lat, :lon => lon }
245 def dms_to_decdeg(captures)
248 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)
249 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)
251 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)
252 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)
254 { :lat => lat, :lon => lon }