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 "uk_postcode"
23 @sources.push "osm_nominatim"
24 elsif @params[:query] =~ /^[A-Z]\d[A-Z]\s*\d[A-Z]\d$/i
25 @sources.push "ca_postcode"
26 @sources.push "osm_nominatim"
28 @sources.push "osm_nominatim"
29 @sources.push "geonames" if defined?(GEONAMES_USERNAME)
36 render :layout => map_layout
41 lat = params[:lat].to_f
42 lon = params[:lon].to_f
43 if lat < -90 || lat > 90
44 @error = "Latitude #{lat} out of range"
45 render :action => "error"
46 elsif lon < -180 || lon > 180
47 @error = "Longitude #{lon} out of range"
48 render :action => "error"
50 @results = [{ :lat => lat, :lon => lon,
51 :zoom => params[:zoom],
52 :name => "#{lat}, #{lon}" }]
54 render :action => "results"
58 def search_uk_postcode
59 # get query parameters
60 query = params[:query]
65 # ask npemap.org.uk to do a combined npemap + freethepostcode search
66 response = fetch_text("http://www.npemap.org.uk/cgi/geocoder.fcgi?format=text&postcode=#{escape_query(query)}")
69 unless response =~ /Error/
70 dataline = response.split(/\n/)[1]
71 data = dataline.split(/,/) # easting,northing,postcode,lat,long
72 postcode = data[2].delete("'")
73 zoom = POSTCODE_ZOOM - postcode.count("#")
74 @results.push(:lat => data[3], :lon => data[4], :zoom => zoom,
78 render :action => "results"
79 rescue StandardError => ex
80 @error = "Error contacting www.npemap.org.uk: #{ex}"
81 render :action => "error"
84 def search_ca_postcode
85 # get query parameters
86 query = params[:query]
89 # ask geocoder.ca (note - they have a per-day limit)
90 response = fetch_xml("http://geocoder.ca/?geoit=XML&postal=#{escape_query(query)}")
93 if response.get_elements("geodata/error").empty?
94 @results.push(:lat => response.text("geodata/latt"),
95 :lon => response.text("geodata/longt"),
96 :zoom => POSTCODE_ZOOM,
97 :name => query.upcase)
100 render :action => "results"
101 rescue StandardError => ex
102 @error = "Error contacting geocoder.ca: #{ex}"
103 render :action => "error"
106 def search_osm_nominatim
107 # get query parameters
108 query = params[:query]
109 minlon = params[:minlon]
110 minlat = params[:minlat]
111 maxlon = params[:maxlon]
112 maxlat = params[:maxlat]
115 if minlon && minlat && maxlon && maxlat
116 viewbox = "&viewbox=#{minlon},#{maxlat},#{maxlon},#{minlat}"
119 # get objects to excude
120 exclude = "&exclude_place_ids=#{params[:exclude]}" if params[:exclude]
123 response = fetch_xml("http:#{NOMINATIM_URL}search?format=xml&extratags=1&q=#{escape_query(query)}#{viewbox}#{exclude}&accept-language=#{http_accept_language.user_preferred_languages.join(',')}")
125 # extract the results from the response
126 results = response.elements["searchresults"]
128 # extract parameters from more_url
129 more_url_params = CGI.parse(URI.parse(results.attributes["more_url"]).query)
131 # create result array
134 # create parameter hash for "more results" link
135 @more_params = params
136 .permit(:query, :minlon, :minlat, :maxlon, :maxlat, :exclude)
137 .merge(:exclude => more_url_params["exclude_place_ids"].first)
140 results.elements.each("place") do |place|
141 lat = place.attributes["lat"]
142 lon = place.attributes["lon"]
143 klass = place.attributes["class"]
144 type = place.attributes["type"]
145 name = place.attributes["display_name"]
146 min_lat, max_lat, min_lon, max_lon = place.attributes["boundingbox"].split(",")
147 prefix_name = if type.empty?
150 t "geocoder.search_osm_nominatim.prefix.#{klass}.#{type}", :default => type.tr("_", " ").capitalize
152 if klass == "boundary" && type == "administrative"
153 rank = (place.attributes["place_rank"].to_i + 1) / 2
154 prefix_name = t "geocoder.search_osm_nominatim.admin_levels.level#{rank}", :default => prefix_name
155 place.elements["extratags"].elements.each("tag") do |extratag|
156 if extratag.attributes["key"] == "place"
157 prefix_name = t "geocoder.search_osm_nominatim.prefix.place.#{extratag.attributes['value']}", :default => prefix_name
161 prefix = t "geocoder.search_osm_nominatim.prefix_format", :name => prefix_name
162 object_type = place.attributes["osm_type"]
163 object_id = place.attributes["osm_id"]
165 @results.push(:lat => lat, :lon => lon,
166 :min_lat => min_lat, :max_lat => max_lat,
167 :min_lon => min_lon, :max_lon => max_lon,
168 :prefix => prefix, :name => name,
169 :type => object_type, :id => object_id)
172 render :action => "results"
173 rescue StandardError => ex
174 @error = "Error contacting nominatim.openstreetmap.org: #{ex}"
175 render :action => "error"
179 # get query parameters
180 query = params[:query]
182 # get preferred language
183 lang = I18n.locale.to_s.split("-").first
185 # create result array
189 response = fetch_xml("http://api.geonames.org/search?q=#{escape_query(query)}&lang=#{lang}&maxRows=20&username=#{GEONAMES_USERNAME}")
192 response.elements.each("geonames/geoname") do |geoname|
193 lat = geoname.text("lat")
194 lon = geoname.text("lng")
195 name = geoname.text("name")
196 country = geoname.text("countryName")
198 @results.push(:lat => lat, :lon => lon,
199 :zoom => GEONAMES_ZOOM,
201 :suffix => ", #{country}")
204 render :action => "results"
205 rescue StandardError => ex
206 @error = "Error contacting api.geonames.org: #{ex}"
207 render :action => "error"
210 def search_osm_nominatim_reverse
211 # get query parameters
216 # create result array
220 response = fetch_xml("http:#{NOMINATIM_URL}reverse?lat=#{lat}&lon=#{lon}&zoom=#{zoom}&accept-language=#{http_accept_language.user_preferred_languages.join(',')}")
223 response.elements.each("reversegeocode/result") do |result|
224 lat = result.attributes["lat"]
225 lon = result.attributes["lon"]
226 object_type = result.attributes["osm_type"]
227 object_id = result.attributes["osm_id"]
228 description = result.text
230 @results.push(:lat => lat, :lon => lon,
232 :name => description,
233 :type => object_type, :id => object_id)
236 render :action => "results"
237 rescue StandardError => ex
238 @error = "Error contacting nominatim.openstreetmap.org: #{ex}"
239 render :action => "error"
242 def search_geonames_reverse
243 # get query parameters
247 # get preferred language
248 lang = I18n.locale.to_s.split("-").first
250 # create result array
254 response = fetch_xml("http://api.geonames.org/countrySubdivision?lat=#{lat}&lng=#{lon}&lang=#{lang}&username=#{GEONAMES_USERNAME}")
257 response.elements.each("geonames/countrySubdivision") do |geoname|
258 name = geoname.text("adminName1")
259 country = geoname.text("countryName")
261 @results.push(:lat => lat, :lon => lon,
262 :zoom => GEONAMES_ZOOM,
264 :suffix => ", #{country}")
267 render :action => "results"
268 rescue StandardError => ex
269 @error = "Error contacting api.geonames.org: #{ex}"
270 render :action => "error"
276 response = OSM.http_client.get(URI.parse(url))
281 raise response.status.to_s
286 REXML::Document.new(fetch_text(url))
289 def escape_query(query)
294 if query = params[:query]
297 if latlon = query.match(/^([NS])\s*(\d{1,3}(\.\d*)?)\W*([EW])\s*(\d{1,3}(\.\d*)?)$/).try(:captures) # [NSEW] decimal degrees
298 params.merge!(nsew_to_decdeg(latlon)).delete(:query)
299 elsif latlon = query.match(/^(\d{1,3}(\.\d*)?)\s*([NS])\W*(\d{1,3}(\.\d*)?)\s*([EW])$/).try(:captures) # decimal degrees [NSEW]
300 params.merge!(nsew_to_decdeg(latlon)).delete(:query)
302 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
303 params.merge!(ddm_to_decdeg(latlon)).delete(:query)
304 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]
305 params.merge!(ddm_to_decdeg(latlon)).delete(:query)
307 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
308 params.merge!(dms_to_decdeg(latlon)).delete(:query)
309 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]
310 params.merge!(dms_to_decdeg(latlon)).delete(:query)
312 elsif latlon = query.match(/^\s*([+-]?\d+(\.\d*)?)\s*[\s,]\s*([+-]?\d+(\.\d*)?)\s*$/)
313 params.merge!(:lat => latlon[1].to_f, :lon => latlon[3].to_f).delete(:query)
317 params.permit(:query, :lat, :lon, :zoom, :minlat, :minlon, :maxlat, :maxlon)
320 def nsew_to_decdeg(captures)
323 lat = !captures[2].casecmp("s").zero? ? captures[0].to_f : -captures[0].to_f
324 lon = !captures[5].casecmp("w").zero? ? captures[3].to_f : -captures[3].to_f
326 lat = !captures[0].casecmp("s").zero? ? captures[1].to_f : -captures[1].to_f
327 lon = !captures[3].casecmp("w").zero? ? captures[4].to_f : -captures[4].to_f
329 { :lat => lat, :lon => lon }
332 def ddm_to_decdeg(captures)
335 lat = !captures[3].casecmp("s").zero? ? captures[0].to_f + captures[1].to_f / 60 : -(captures[0].to_f + captures[1].to_f / 60)
336 lon = !captures[7].casecmp("w").zero? ? captures[4].to_f + captures[5].to_f / 60 : -(captures[4].to_f + captures[5].to_f / 60)
338 lat = !captures[0].casecmp("s").zero? ? captures[1].to_f + captures[2].to_f / 60 : -(captures[1].to_f + captures[2].to_f / 60)
339 lon = !captures[4].casecmp("w").zero? ? captures[5].to_f + captures[6].to_f / 60 : -(captures[5].to_f + captures[6].to_f / 60)
341 { :lat => lat, :lon => lon }
344 def dms_to_decdeg(captures)
347 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)
348 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)
350 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)
351 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)
353 { :lat => lat, :lon => lon }