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]
11 @params = normalize_params
14 if @params[:lat] && @params[:lon]
15 @sources.push "latlon"
16 @sources.push "osm_nominatim_reverse"
17 @sources.push "geonames_reverse" if defined?(GEONAMES_USERNAME)
19 if @params[:query] =~ /^\d{5}(-\d{4})?$/
20 @sources.push "osm_nominatim"
21 elsif @params[:query] =~ /^(GIR 0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKS-UW])\s*[0-9][ABD-HJLNP-UW-Z]{2})$/i
22 @sources.push "osm_nominatim"
23 elsif @params[:query] =~ /^[A-Z]\d[A-Z]\s*\d[A-Z]\d$/i
24 @sources.push "ca_postcode"
25 @sources.push "osm_nominatim"
27 @sources.push "osm_nominatim"
28 @sources.push "geonames" if defined?(GEONAMES_USERNAME)
35 render :layout => map_layout
40 lat = params[:lat].to_f
41 lon = params[:lon].to_f
43 if params[:latlon_digits]
44 # We've got two nondescript numbers for a query, which can mean both "lat, lon" or "lon, lat".
47 if lat >= -90 && lat <= 90 && lon >= -180 && lon <= 180
48 @results.push(:lat => lat, :lon => lon,
49 :zoom => params[:zoom],
50 :name => "#{lat}, #{lon}")
52 if lon >= -90 && lon <= 90 && lat >= -180 && lat <= 180
53 @results.push(:lat => lon, :lon => lat,
54 :zoom => params[:zoom],
55 :name => "#{lon}, #{lat}")
59 @error = "Latitude or longitude are out of range"
60 render :action => "error"
62 render :action => "results"
66 # Coordinates in a query have come with markers for latitude and longitude.
67 if lat < -90 || lat > 90
68 @error = "Latitude #{lat} out of range"
69 render :action => "error"
70 elsif lon < -180 || lon > 180
71 @error = "Longitude #{lon} out of range"
72 render :action => "error"
74 @results = [{ :lat => lat, :lon => lon,
75 :zoom => params[:zoom],
76 :name => "#{lat}, #{lon}" }]
78 render :action => "results"
83 def search_ca_postcode
84 # get query parameters
85 query = params[:query]
88 # ask geocoder.ca (note - they have a per-day limit)
89 response = fetch_xml("https://geocoder.ca/?geoit=XML&postal=#{escape_query(query)}")
92 if response.get_elements("geodata/error").empty?
93 @results.push(:lat => response.text("geodata/latt"),
94 :lon => response.text("geodata/longt"),
95 :zoom => POSTCODE_ZOOM,
96 :name => query.upcase)
99 render :action => "results"
100 rescue StandardError => ex
101 @error = "Error contacting geocoder.ca: #{ex}"
102 render :action => "error"
105 def search_osm_nominatim
106 # get query parameters
107 query = params[:query]
108 minlon = params[:minlon]
109 minlat = params[:minlat]
110 maxlon = params[:maxlon]
111 maxlat = params[:maxlat]
114 viewbox = "&viewbox=#{minlon},#{maxlat},#{maxlon},#{minlat}" if minlon && minlat && maxlon && maxlat
116 # get objects to excude
117 exclude = "&exclude_place_ids=#{params[:exclude]}" if params[:exclude]
120 response = fetch_xml("#{NOMINATIM_URL}search?format=xml&extratags=1&q=#{escape_query(query)}#{viewbox}#{exclude}&accept-language=#{http_accept_language.user_preferred_languages.join(',')}")
122 # extract the results from the response
123 results = response.elements["searchresults"]
125 # extract parameters from more_url
126 more_url_params = CGI.parse(URI.parse(results.attributes["more_url"]).query)
128 # create result array
131 # create parameter hash for "more results" link
132 @more_params = params
133 .permit(:query, :minlon, :minlat, :maxlon, :maxlat, :exclude)
134 .merge(:exclude => more_url_params["exclude_place_ids"].first)
137 results.elements.each("place") do |place|
138 lat = place.attributes["lat"]
139 lon = place.attributes["lon"]
140 klass = place.attributes["class"]
141 type = place.attributes["type"]
142 name = place.attributes["display_name"]
143 min_lat, max_lat, min_lon, max_lon = place.attributes["boundingbox"].split(",")
144 prefix_name = if type.empty?
147 t "geocoder.search_osm_nominatim.prefix.#{klass}.#{type}", :default => type.tr("_", " ").capitalize
149 if klass == "boundary" && type == "administrative"
150 rank = (place.attributes["place_rank"].to_i + 1) / 2
151 prefix_name = t "geocoder.search_osm_nominatim.admin_levels.level#{rank}", :default => prefix_name
152 place.elements["extratags"].elements.each("tag") do |extratag|
153 prefix_name = t "geocoder.search_osm_nominatim.prefix.place.#{extratag.attributes['value']}", :default => prefix_name if extratag.attributes["key"] == "place"
156 prefix = t "geocoder.search_osm_nominatim.prefix_format", :name => prefix_name
157 object_type = place.attributes["osm_type"]
158 object_id = place.attributes["osm_id"]
160 @results.push(:lat => lat, :lon => lon,
161 :min_lat => min_lat, :max_lat => max_lat,
162 :min_lon => min_lon, :max_lon => max_lon,
163 :prefix => prefix, :name => name,
164 :type => object_type, :id => object_id)
167 render :action => "results"
168 rescue StandardError => ex
169 @error = "Error contacting nominatim.openstreetmap.org: #{ex}"
170 render :action => "error"
174 # get query parameters
175 query = params[:query]
177 # get preferred language
178 lang = I18n.locale.to_s.split("-").first
180 # create result array
184 response = fetch_xml("http://api.geonames.org/search?q=#{escape_query(query)}&lang=#{lang}&maxRows=20&username=#{GEONAMES_USERNAME}")
187 response.elements.each("geonames/geoname") do |geoname|
188 lat = geoname.text("lat")
189 lon = geoname.text("lng")
190 name = geoname.text("name")
191 country = geoname.text("countryName")
193 @results.push(:lat => lat, :lon => lon,
194 :zoom => GEONAMES_ZOOM,
196 :suffix => ", #{country}")
199 render :action => "results"
200 rescue StandardError => ex
201 @error = "Error contacting api.geonames.org: #{ex}"
202 render :action => "error"
205 def search_osm_nominatim_reverse
206 # get query parameters
211 # create result array
215 response = fetch_xml("#{NOMINATIM_URL}reverse?lat=#{lat}&lon=#{lon}&zoom=#{zoom}&accept-language=#{http_accept_language.user_preferred_languages.join(',')}")
218 response.elements.each("reversegeocode/result") do |result|
219 lat = result.attributes["lat"]
220 lon = result.attributes["lon"]
221 object_type = result.attributes["osm_type"]
222 object_id = result.attributes["osm_id"]
223 description = result.text
225 @results.push(:lat => lat, :lon => lon,
227 :name => description,
228 :type => object_type, :id => object_id)
231 render :action => "results"
232 rescue StandardError => ex
233 @error = "Error contacting nominatim.openstreetmap.org: #{ex}"
234 render :action => "error"
237 def search_geonames_reverse
238 # get query parameters
242 # get preferred language
243 lang = I18n.locale.to_s.split("-").first
245 # create result array
249 response = fetch_xml("http://api.geonames.org/countrySubdivision?lat=#{lat}&lng=#{lon}&lang=#{lang}&username=#{GEONAMES_USERNAME}")
252 response.elements.each("geonames/countrySubdivision") do |geoname|
253 name = geoname.text("adminName1")
254 country = geoname.text("countryName")
256 @results.push(:lat => lat, :lon => lon,
257 :zoom => GEONAMES_ZOOM,
259 :suffix => ", #{country}")
262 render :action => "results"
263 rescue StandardError => ex
264 @error = "Error contacting api.geonames.org: #{ex}"
265 render :action => "error"
271 response = OSM.http_client.get(URI.parse(url))
276 raise response.status.to_s
281 REXML::Document.new(fetch_text(url))
284 def escape_query(query)
289 if query = params[:query]
292 if latlon = query.match(/^([NS])\s*(\d{1,3}(\.\d*)?)\W*([EW])\s*(\d{1,3}(\.\d*)?)$/).try(:captures) # [NSEW] decimal degrees
293 params.merge!(nsew_to_decdeg(latlon)).delete(:query)
294 elsif latlon = query.match(/^(\d{1,3}(\.\d*)?)\s*([NS])\W*(\d{1,3}(\.\d*)?)\s*([EW])$/).try(:captures) # decimal degrees [NSEW]
295 params.merge!(nsew_to_decdeg(latlon)).delete(:query)
297 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
298 params.merge!(ddm_to_decdeg(latlon)).delete(:query)
299 elsif latlon = 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]
300 params.merge!(ddm_to_decdeg(latlon)).delete(:query)
302 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
303 params.merge!(dms_to_decdeg(latlon)).delete(:query)
304 elsif latlon = 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]
305 params.merge!(dms_to_decdeg(latlon)).delete(:query)
307 elsif latlon = query.match(/^\s*([+-]?\d+(\.\d*)?)\s*[\s,]\s*([+-]?\d+(\.\d*)?)\s*$/)
308 params.merge!(:lat => latlon[1].to_f, :lon => latlon[3].to_f, :latlon_digits => true).delete(:query)
312 params.permit(:query, :lat, :lon, :latlon_digits, :zoom, :minlat, :minlon, :maxlat, :maxlon)
315 def nsew_to_decdeg(captures)
318 lat = !captures[2].casecmp("s").zero? ? captures[0].to_f : -captures[0].to_f
319 lon = !captures[5].casecmp("w").zero? ? captures[3].to_f : -captures[3].to_f
321 lat = !captures[0].casecmp("s").zero? ? captures[1].to_f : -captures[1].to_f
322 lon = !captures[3].casecmp("w").zero? ? captures[4].to_f : -captures[4].to_f
324 { :lat => lat, :lon => lon }
327 def ddm_to_decdeg(captures)
330 lat = !captures[3].casecmp("s").zero? ? captures[0].to_f + captures[1].to_f / 60 : -(captures[0].to_f + captures[1].to_f / 60)
331 lon = !captures[7].casecmp("w").zero? ? captures[4].to_f + captures[5].to_f / 60 : -(captures[4].to_f + captures[5].to_f / 60)
333 lat = !captures[0].casecmp("s").zero? ? captures[1].to_f + captures[2].to_f / 60 : -(captures[1].to_f + captures[2].to_f / 60)
334 lon = !captures[4].casecmp("w").zero? ? captures[5].to_f + captures[6].to_f / 60 : -(captures[5].to_f + captures[6].to_f / 60)
336 { :lat => lat, :lon => lon }
339 def dms_to_decdeg(captures)
342 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)
343 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)
345 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)
346 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)
348 { :lat => lat, :lon => lon }