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(:name => "latlon", :url => root_path)
17 @sources.push(:name => "osm_nominatim_reverse", :url => nominatim_reverse_url(:format => "html"))
19 @sources.push(:name => "osm_nominatim", :url => nominatim_url(:format => "html"))
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
75 response = fetch_xml(nominatim_url(:format => "xml"))
77 # extract the results from the response
78 results = response.elements["searchresults"]
83 # create parameter hash for "more results" link
85 .permit(:query, :minlon, :minlat, :maxlon, :maxlat, :exclude)
86 .merge(:exclude => results.attributes["exclude_place_ids"])
89 results.elements.each("place") do |place|
90 lat = place.attributes["lat"]
91 lon = place.attributes["lon"]
92 klass = place.attributes["class"]
93 type = place.attributes["type"]
94 name = place.attributes["display_name"]
95 min_lat, max_lat, min_lon, max_lon = place.attributes["boundingbox"].split(",")
96 prefix_name = if type.empty?
99 t "geocoder.search_osm_nominatim.prefix.#{klass}.#{type}", :default => type.tr("_", " ").capitalize
101 if klass == "boundary" && type == "administrative"
102 rank = (place.attributes["address_rank"].to_i + 1) / 2
103 prefix_name = t "geocoder.search_osm_nominatim.admin_levels.level#{rank}", :default => prefix_name
104 place.elements["extratags"].elements.each("tag") do |extratag|
105 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"
108 prefix = t ".prefix_format", :name => prefix_name
109 object_type = place.attributes["osm_type"]
110 object_id = place.attributes["osm_id"]
112 @results.push(:lat => lat, :lon => lon,
113 :min_lat => min_lat, :max_lat => max_lat,
114 :min_lon => min_lon, :max_lon => max_lon,
115 :prefix => prefix, :name => name,
116 :type => object_type, :id => object_id)
119 render :action => "results"
120 rescue StandardError => e
121 host = URI(Settings.nominatim_url).host
122 @error = "Error contacting #{host}: #{e}"
123 render :action => "error"
126 def search_osm_nominatim_reverse
127 # get query parameters
130 # create result array
134 response = fetch_xml(nominatim_reverse_url(:format => "xml"))
137 response.elements.each("reversegeocode/result") do |result|
138 lat = result.attributes["lat"]
139 lon = result.attributes["lon"]
140 object_type = result.attributes["osm_type"]
141 object_id = result.attributes["osm_id"]
142 description = result.text
144 @results.push(:lat => lat, :lon => lon,
146 :name => description,
147 :type => object_type, :id => object_id)
150 render :action => "results"
151 rescue StandardError => e
152 host = URI(Settings.nominatim_url).host
153 @error = "Error contacting #{host}: #{e}"
154 render :action => "error"
159 def nominatim_url(format: nil)
160 # get query parameters
161 query = params[:query]
162 minlon = params[:minlon]
163 minlat = params[:minlat]
164 maxlon = params[:maxlon]
165 maxlat = params[:maxlat]
168 viewbox = "&viewbox=#{minlon},#{maxlat},#{maxlon},#{minlat}" if minlon && minlat && maxlon && maxlat
170 # get objects to excude
171 exclude = "&exclude_place_ids=#{params[:exclude]}" if params[:exclude]
174 "#{Settings.nominatim_url}search?format=#{format}&extratags=1&q=#{escape_query(query)}#{viewbox}#{exclude}&accept-language=#{http_accept_language.user_preferred_languages.join(',')}"
177 def nominatim_reverse_url(format: nil)
178 # get query parameters
184 "#{Settings.nominatim_url}reverse?format=#{format}&lat=#{lat}&lon=#{lon}&zoom=#{zoom}&accept-language=#{http_accept_language.user_preferred_languages.join(',')}"
188 response = OSM.http_client.get(URI.parse(url))
193 raise response.status.to_s
198 REXML::Document.new(fetch_text(url))
201 def escape_query(query)
206 if query = params[:query]
209 if latlon = query.match(/^([NS])\s*(\d{1,3}(\.\d*)?)\W*([EW])\s*(\d{1,3}(\.\d*)?)$/).try(:captures) || # [NSEW] decimal degrees
210 query.match(/^(\d{1,3}(\.\d*)?)\s*([NS])\W*(\d{1,3}(\.\d*)?)\s*([EW])$/).try(:captures) # decimal degrees [NSEW]
211 params.merge!(nsew_to_decdeg(latlon)).delete(:query)
213 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
214 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]
215 params.merge!(ddm_to_decdeg(latlon)).delete(:query)
217 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
218 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]
219 params.merge!(dms_to_decdeg(latlon)).delete(:query)
221 elsif latlon = query.match(%r{^([+-]?\d+(\.\d*)?)(?:\s+|\s*[,/]\s*)([+-]?\d+(\.\d*)?)$})
222 params.merge!(:lat => latlon[1].to_f, :lon => latlon[3].to_f).delete(:query)
224 params[:latlon_digits] = true unless params[:whereami]
228 params.permit(:query, :lat, :lon, :latlon_digits, :zoom, :minlat, :minlon, :maxlat, :maxlon)
231 def nsew_to_decdeg(captures)
234 lat = captures[2].casecmp("s").zero? ? -captures[0].to_f : captures[0].to_f
235 lon = captures[5].casecmp("w").zero? ? -captures[3].to_f : captures[3].to_f
237 lat = captures[0].casecmp("s").zero? ? -captures[1].to_f : captures[1].to_f
238 lon = captures[3].casecmp("w").zero? ? -captures[4].to_f : captures[4].to_f
240 { :lat => lat, :lon => lon }
243 def ddm_to_decdeg(captures)
246 lat = captures[3].casecmp("s").zero? ? -(captures[0].to_f + (captures[1].to_f / 60)) : captures[0].to_f + (captures[1].to_f / 60)
247 lon = captures[7].casecmp("w").zero? ? -(captures[4].to_f + (captures[5].to_f / 60)) : captures[4].to_f + (captures[5].to_f / 60)
249 lat = captures[0].casecmp("s").zero? ? -(captures[1].to_f + (captures[2].to_f / 60)) : captures[1].to_f + (captures[2].to_f / 60)
250 lon = captures[4].casecmp("w").zero? ? -(captures[5].to_f + (captures[6].to_f / 60)) : captures[5].to_f + (captures[6].to_f / 60)
252 { :lat => lat, :lon => lon }
255 def dms_to_decdeg(captures)
258 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)
259 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)
261 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)
262 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)
264 { :lat => lat, :lon => lon }