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 => params[:lat], :lon => params[:lon],
39 :zoom => params[:zoom],
40 :name => "#{params[:lat]}, #{params[:lon]}")
43 if lon >= -90 && lon <= 90 && lat >= -180 && lat <= 180
44 @results.push(:lat => params[:lon], :lon => params[:lat],
45 :zoom => params[:zoom],
46 :name => "#{params[:lon]}, #{params[: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 => params[:lat], :lon => params[:lon],
65 :zoom => params[:zoom],
66 :name => "#{params[:lat]}, #{params[: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
106 place_tags = %w[linked_place place]
107 place.elements["extratags"].elements.each("tag") do |extratag|
108 border_type = t "geocoder.search_osm_nominatim.border_types.#{extratag.attributes['value']}", :default => border_type if extratag.attributes["key"] == "border_type"
109 place_type = t "geocoder.search_osm_nominatim.prefix.place.#{extratag.attributes['value']}", :default => place_type if place_tags.include?(extratag.attributes["key"])
111 prefix_name = place_type || border_type || prefix_name
113 prefix = t ".prefix_format", :name => prefix_name
114 object_type = place.attributes["osm_type"]
115 object_id = place.attributes["osm_id"]
117 @results.push(:lat => lat, :lon => lon,
118 :min_lat => min_lat, :max_lat => max_lat,
119 :min_lon => min_lon, :max_lon => max_lon,
120 :prefix => prefix, :name => name,
121 :type => object_type, :id => object_id)
124 render :action => "results"
125 rescue StandardError => e
126 host = URI(Settings.nominatim_url).host
127 @error = "Error contacting #{host}: #{e}"
128 render :action => "error"
131 def search_osm_nominatim_reverse
132 # get query parameters
135 # create result array
139 response = fetch_xml(nominatim_reverse_url(:format => "xml"))
142 response.elements.each("reversegeocode/result") do |result|
143 lat = result.attributes["lat"]
144 lon = result.attributes["lon"]
145 object_type = result.attributes["osm_type"]
146 object_id = result.attributes["osm_id"]
147 description = result.text
149 @results.push(:lat => lat, :lon => lon,
151 :name => description,
152 :type => object_type, :id => object_id)
155 render :action => "results"
156 rescue StandardError => e
157 host = URI(Settings.nominatim_url).host
158 @error = "Error contacting #{host}: #{e}"
159 render :action => "error"
164 def nominatim_url(format: nil)
165 # get query parameters
166 query = params[:query]
167 minlon = params[:minlon]
168 minlat = params[:minlat]
169 maxlon = params[:maxlon]
170 maxlat = params[:maxlat]
173 viewbox = "&viewbox=#{minlon},#{maxlat},#{maxlon},#{minlat}" if minlon && minlat && maxlon && maxlat
175 # get objects to excude
176 exclude = "&exclude_place_ids=#{params[:exclude]}" if params[:exclude]
179 "#{Settings.nominatim_url}search?format=#{format}&extratags=1&q=#{escape_query(query)}#{viewbox}#{exclude}&accept-language=#{http_accept_language.user_preferred_languages.join(',')}"
182 def nominatim_reverse_url(format: nil)
183 # get query parameters
189 "#{Settings.nominatim_url}reverse?format=#{format}&lat=#{lat}&lon=#{lon}&zoom=#{zoom}&accept-language=#{http_accept_language.user_preferred_languages.join(',')}"
193 response = OSM.http_client.get(URI.parse(url))
198 raise response.status.to_s
203 REXML::Document.new(fetch_text(url))
206 def escape_query(query)
211 if query = params[:query]
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)
218 elsif latlon = query.match(%r{^(?<lat>[+-]?\d+(?:\.\d+)?)(?:\s+|\s*[,/]\s*)(?<lon>[+-]?\d+(?:\.\d+)?)$})
219 params.merge!(:lat => latlon["lat"], :lon => latlon["lon"]).delete(:query)
221 params[:latlon_digits] = true
225 params.permit(:query, :lat, :lon, :latlon_digits, :zoom, :minlat, :minlon, :maxlat, :maxlon)
228 def dms_regexp(name_prefix)
230 (?: (?<#{name_prefix}d>\d{1,3}(?:\.\d+)?)°? ) |
231 (?: (?<#{name_prefix}d>\d{1,3})°?\s*(?<#{name_prefix}m>\d{1,2}(?:\.\d+)?)['′]? ) |
232 (?: (?<#{name_prefix}d>\d{1,3})°?\s*(?<#{name_prefix}m>\d{1,2})['′]?\s*(?<#{name_prefix}s>\d{1,2}(?:\.\d+)?)["″]? )
236 def to_decdeg(captures)
237 ns = captures.fetch("ns").casecmp?("s") ? -1 : 1
238 nsd = BigDecimal(captures.fetch("nsd", "0"))
239 nsm = BigDecimal(captures.fetch("nsm", "0"))
240 nss = BigDecimal(captures.fetch("nss", "0"))
242 ew = captures.fetch("ew").casecmp?("w") ? -1 : 1
243 ewd = BigDecimal(captures.fetch("ewd", "0"))
244 ewm = BigDecimal(captures.fetch("ewm", "0"))
245 ews = BigDecimal(captures.fetch("ews", "0"))
247 lat = ns * (nsd + (nsm / 60) + (nss / 3600))
248 lon = ew * (ewd + (ewm / 60) + (ews / 3600))
250 { :lat => lat.round(6).to_s("F"), :lon => lon.round(6).to_s("F") }