1 class GeocoderController < ApplicationController
3 require "rexml/document"
4 include NominatimMethods
6 before_action :authorize_web
7 before_action :set_locale
8 before_action :require_oauth, :only => [:search]
10 authorize_resource :class => false
12 before_action :normalize_params, :only => [:search]
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")))
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")))
30 render :layout => map_layout
35 lat = params[:lat].to_f
36 lon = params[:lon].to_f
38 if params[:latlon_digits]
39 # We've got two nondescript numbers for a query, which can mean both "lat, lon" or "lon, lat".
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]}")
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]}")
55 @error = "Latitude or longitude are out of range"
56 render :action => "error"
58 render :action => "results"
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"
69 @results = [{ :lat => params[:lat], :lon => params[:lon],
70 :zoom => params[:zoom],
71 :name => "#{params[:lat]}, #{params[:lon]}" }]
73 render :action => "results"
78 def search_osm_nominatim
80 response = fetch_xml(nominatim_query_url(:format => "xml"))
82 # extract the results from the response
83 results = response.elements["searchresults"]
88 # create parameter hash for "more results" link
90 .permit(:query, :minlon, :minlat, :maxlon, :maxlat, :exclude)
91 .merge(:exclude => results.attributes["exclude_place_ids"])
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?
104 t "geocoder.search_osm_nominatim.prefix.#{klass}.#{type}", :default => type.tr("_", " ").capitalize
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
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"])
116 prefix_name = place_type || border_type || prefix_name
118 prefix = t ".prefix_format", :name => prefix_name
119 object_type = place.attributes["osm_type"]
120 object_id = place.attributes["osm_id"]
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)
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"
136 def search_osm_nominatim_reverse
137 # get query parameters
140 # create result array
144 response = fetch_xml(nominatim_reverse_query_url(:format => "xml"))
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
154 @results.push(:lat => lat, :lon => lon,
156 :name => description,
157 :type => object_type, :id => object_id)
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"
170 response = OSM.http_client.get(URI.parse(url))
175 raise response.status.to_s
180 REXML::Document.new(fetch_text(url))
184 if (query = params[:query])
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)
191 elsif (latlon = query.match(%r{^(?<lat>[+-]?\d+(?:\.\d+)?)(?:\s+|\s*[,/]\s*)(?<lon>[+-]?\d+(?:\.\d+)?)$}))
192 params.merge!(latlon.named_captures).delete(:query)
194 params[:latlon_digits] = true
199 def dms_regexp(name_prefix)
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+)?)["″]? )
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"))
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"))
218 lat = ns * (nsd + (nsm / 60) + (nss / 3600))
219 lon = ew * (ewd + (ewm / 60) + (ews / 3600))
221 { :lat => lat.round(6).to_s("F"), :lon => lon.round(6).to_s("F") }