3 class GeocoderController < ApplicationController
6 require "rexml/document"
8 before_action :authorize_web
9 before_action :set_locale
10 before_action :require_oauth, :only => [:search]
17 if params[:lat] && params[:lon]
18 @sources.push "latlon"
19 @sources.push "osm_nominatim_reverse"
20 @sources.push "geonames_reverse" if defined?(GEONAMES_USERNAME)
22 if params[:query] =~ /^\d{5}(-\d{4})?$/
23 @sources.push "us_postcode"
24 @sources.push "osm_nominatim"
25 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
26 @sources.push "uk_postcode"
27 @sources.push "osm_nominatim"
28 elsif params[:query] =~ /^[A-Z]\d[A-Z]\s*\d[A-Z]\d$/i
29 @sources.push "ca_postcode"
30 @sources.push "osm_nominatim"
32 @sources.push "osm_nominatim"
33 @sources.push "geonames" if defined?(GEONAMES_USERNAME)
38 render :text => "", :status => :bad_request
40 render :layout => map_layout
45 lat = params[:lat].to_f
46 lon = params[:lon].to_f
47 if lat < -90 || lat > 90
48 @error = "Latitude #{lat} out of range"
49 render :action => "error"
50 elsif lon < -180 || lon > 180
51 @error = "Longitude #{lon} out of range"
52 render :action => "error"
54 @results = [{ :lat => lat, :lon => lon,
55 :zoom => params[:zoom],
56 :name => "#{lat}, #{lon}" }]
58 render :action => "results"
62 def search_us_postcode
63 # get query parameters
64 query = params[:query]
69 # ask geocoder.us (they have a non-commercial use api)
70 response = fetch_text("http://rpc.geocoder.us/service/csv?zip=#{escape_query(query)}")
73 unless response =~ /couldn't find this zip/
74 data = response.split(/\s*,\s+/) # lat,long,town,state,zip
75 @results.push(:lat => data[0], :lon => data[1],
76 :zoom => POSTCODE_ZOOM,
77 :prefix => "#{data[2]}, #{data[3]},",
81 render :action => "results"
82 rescue StandardError => ex
83 @error = "Error contacting rpc.geocoder.us: #{ex}"
84 render :action => "error"
87 def search_uk_postcode
88 # get query parameters
89 query = params[:query]
94 # ask npemap.org.uk to do a combined npemap + freethepostcode search
95 response = fetch_text("http://www.npemap.org.uk/cgi/geocoder.fcgi?format=text&postcode=#{escape_query(query)}")
98 unless response =~ /Error/
99 dataline = response.split(/\n/)[1]
100 data = dataline.split(/,/) # easting,northing,postcode,lat,long
101 postcode = data[2].delete("'")
102 zoom = POSTCODE_ZOOM - postcode.count("#")
103 @results.push(:lat => data[3], :lon => data[4], :zoom => zoom,
107 render :action => "results"
108 rescue StandardError => ex
109 @error = "Error contacting www.npemap.org.uk: #{ex}"
110 render :action => "error"
113 def search_ca_postcode
114 # get query parameters
115 query = params[:query]
118 # ask geocoder.ca (note - they have a per-day limit)
119 response = fetch_xml("http://geocoder.ca/?geoit=XML&postal=#{escape_query(query)}")
122 if response.get_elements("geodata/error").empty?
123 @results.push(:lat => response.get_text("geodata/latt").to_s,
124 :lon => response.get_text("geodata/longt").to_s,
125 :zoom => POSTCODE_ZOOM,
126 :name => query.upcase)
129 render :action => "results"
130 rescue StandardError => ex
131 @error = "Error contacting geocoder.ca: #{ex}"
132 render :action => "error"
135 def search_osm_nominatim
136 # get query parameters
137 query = params[:query]
138 minlon = params[:minlon]
139 minlat = params[:minlat]
140 maxlon = params[:maxlon]
141 maxlat = params[:maxlat]
144 if minlon && minlat && maxlon && maxlat
145 viewbox = "&viewbox=#{minlon},#{maxlat},#{maxlon},#{minlat}"
148 # get objects to excude
149 exclude = "&exclude_place_ids=#{params[:exclude]}" if params[:exclude]
152 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(',')}")
154 # extract the results from the response
155 results = response.elements["searchresults"]
157 # extract parameters from more_url
158 more_url_params = CGI.parse(URI.parse(results.attributes["more_url"]).query)
160 # create result array
163 # create parameter hash for "more results" link
164 @more_params = params.merge(:exclude => more_url_params["exclude_place_ids"].first)
167 results.elements.each("place") do |place|
168 lat = place.attributes["lat"].to_s
169 lon = place.attributes["lon"].to_s
170 klass = place.attributes["class"].to_s
171 type = place.attributes["type"].to_s
172 name = place.attributes["display_name"].to_s
173 min_lat, max_lat, min_lon, max_lon = place.attributes["boundingbox"].to_s.split(",")
174 prefix_name = if type.empty?
177 t "geocoder.search_osm_nominatim.prefix.#{klass}.#{type}", :default => type.tr("_", " ").capitalize
179 if klass == "boundary" && type == "administrative"
180 rank = (place.attributes["place_rank"].to_i + 1) / 2
181 prefix_name = t "geocoder.search_osm_nominatim.admin_levels.level#{rank}", :default => prefix_name
182 place.elements["extratags"].elements.each("tag") do |extratag|
183 if extratag.attributes["key"] == "place"
184 prefix_name = t "geocoder.search_osm_nominatim.prefix.place.#{extratag.attributes['value']}", :default => prefix_name
188 prefix = t "geocoder.search_osm_nominatim.prefix_format", :name => prefix_name
189 object_type = place.attributes["osm_type"]
190 object_id = place.attributes["osm_id"]
192 @results.push(:lat => lat, :lon => lon,
193 :min_lat => min_lat, :max_lat => max_lat,
194 :min_lon => min_lon, :max_lon => max_lon,
195 :prefix => prefix, :name => name,
196 :type => object_type, :id => object_id)
199 render :action => "results"
200 rescue StandardError => ex
201 @error = "Error contacting nominatim.openstreetmap.org: #{ex}"
202 render :action => "error"
206 # get query parameters
207 query = params[:query]
209 # get preferred language
210 lang = I18n.locale.to_s.split("-").first
212 # create result array
216 response = fetch_xml("http://api.geonames.org/search?q=#{escape_query(query)}&lang=#{lang}&maxRows=20&username=#{GEONAMES_USERNAME}")
219 response.elements.each("geonames/geoname") do |geoname|
220 lat = geoname.get_text("lat").to_s
221 lon = geoname.get_text("lng").to_s
222 name = geoname.get_text("name").to_s
223 country = geoname.get_text("countryName").to_s
224 @results.push(:lat => lat, :lon => lon,
225 :zoom => GEONAMES_ZOOM,
227 :suffix => ", #{country}")
230 render :action => "results"
231 rescue StandardError => ex
232 @error = "Error contacting api.geonames.org: #{ex}"
233 render :action => "error"
236 def search_osm_nominatim_reverse
237 # get query parameters
242 # create result array
246 response = fetch_xml("http:#{NOMINATIM_URL}reverse?lat=#{lat}&lon=#{lon}&zoom=#{zoom}&accept-language=#{http_accept_language.user_preferred_languages.join(',')}")
249 response.elements.each("reversegeocode/result") do |result|
250 lat = result.attributes["lat"].to_s
251 lon = result.attributes["lon"].to_s
252 object_type = result.attributes["osm_type"]
253 object_id = result.attributes["osm_id"]
254 description = result.get_text.to_s
256 @results.push(:lat => lat, :lon => lon,
258 :name => description,
259 :type => object_type, :id => object_id)
262 render :action => "results"
263 rescue StandardError => ex
264 @error = "Error contacting nominatim.openstreetmap.org: #{ex}"
265 render :action => "error"
268 def search_geonames_reverse
269 # get query parameters
273 # get preferred language
274 lang = I18n.locale.to_s.split("-").first
276 # create result array
280 response = fetch_xml("http://api.geonames.org/countrySubdivision?lat=#{lat}&lng=#{lon}&lang=#{lang}&username=#{GEONAMES_USERNAME}")
283 response.elements.each("geonames/countrySubdivision") do |geoname|
284 name = geoname.get_text("adminName1").to_s
285 country = geoname.get_text("countryName").to_s
286 @results.push(:lat => lat, :lon => lon,
287 :zoom => GEONAMES_ZOOM,
289 :suffix => ", #{country}")
292 render :action => "results"
293 rescue StandardError => ex
294 @error = "Error contacting api.geonames.org: #{ex}"
295 render :action => "error"
301 response = OSM.http_client.get(URI.parse(url))
306 raise response.status.to_s
311 REXML::Document.new(fetch_text(url))
314 def escape_query(query)
315 URI.escape(query, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]", false, "N"))
319 query = params[:query]
324 if latlon = query.match(/^([NS])\s*(\d{1,3}(\.\d*)?)\W*([EW])\s*(\d{1,3}(\.\d*)?)$/).try(:captures) # [NSEW] decimal degrees
325 params.merge!(nsew_to_decdeg(latlon)).delete(:query)
326 elsif latlon = query.match(/^(\d{1,3}(\.\d*)?)\s*([NS])\W*(\d{1,3}(\.\d*)?)\s*([EW])$/).try(:captures) # decimal degrees [NSEW]
327 params.merge!(nsew_to_decdeg(latlon)).delete(:query)
329 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
330 params.merge!(ddm_to_decdeg(latlon)).delete(:query)
331 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]
332 params.merge!(ddm_to_decdeg(latlon)).delete(:query)
334 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
335 params.merge!(dms_to_decdeg(latlon)).delete(:query)
336 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]
337 params.merge!(dms_to_decdeg(latlon)).delete(:query)
339 elsif latlon = query.match(/^\s*([+-]?\d+(\.\d*)?)\s*[\s,]\s*([+-]?\d+(\.\d*)?)\s*$/)
340 params.merge!(:lat => latlon[1].to_f, :lon => latlon[3].to_f).delete(:query)
344 def nsew_to_decdeg(captures)
347 lat = !captures[2].casecmp("s").zero? ? captures[0].to_f : -captures[0].to_f
348 lon = !captures[5].casecmp("w").zero? ? captures[3].to_f : -captures[3].to_f
350 lat = !captures[0].casecmp("s").zero? ? captures[1].to_f : -captures[1].to_f
351 lon = !captures[3].casecmp("w").zero? ? captures[4].to_f : -captures[4].to_f
353 { :lat => lat, :lon => lon }
356 def ddm_to_decdeg(captures)
359 lat = !captures[3].casecmp("s").zero? ? captures[0].to_f + captures[1].to_f / 60 : -(captures[0].to_f + captures[1].to_f / 60)
360 lon = !captures[7].casecmp("w").zero? ? captures[4].to_f + captures[5].to_f / 60 : -(captures[4].to_f + captures[5].to_f / 60)
362 lat = !captures[0].casecmp("s").zero? ? captures[1].to_f + captures[2].to_f / 60 : -(captures[1].to_f + captures[2].to_f / 60)
363 lon = !captures[4].casecmp("w").zero? ? captures[5].to_f + captures[6].to_f / 60 : -(captures[5].to_f + captures[6].to_f / 60)
365 { :lat => lat, :lon => lon }
368 def dms_to_decdeg(captures)
371 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)
372 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)
374 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)
375 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)
377 { :lat => lat, :lon => lon }