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]
16 if params[:lat] && params[:lon]
17 @sources.push "latlon"
18 @sources.push "osm_nominatim_reverse"
19 @sources.push "geonames_reverse" if defined?(GEONAMES_USERNAME)
20 elsif params[:query].match(/^\d{5}(-\d{4})?$/)
21 @sources.push "us_postcode"
22 @sources.push "osm_nominatim"
23 elsif params[:query].match(/^(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)
24 @sources.push "uk_postcode"
25 @sources.push "osm_nominatim"
26 elsif params[:query].match(/^[A-Z]\d[A-Z]\s*\d[A-Z]\d$/i)
27 @sources.push "ca_postcode"
28 @sources.push "osm_nominatim"
30 @sources.push "osm_nominatim"
31 @sources.push "geonames" if defined?(GEONAMES_USERNAME)
34 render :layout => map_layout
38 lat = params[:lat].to_f
39 lon = params[:lon].to_f
40 if lat < -90 || lat > 90
41 @error = "Latitude #{lat} out of range"
42 render :action => "error"
43 elsif lon < -180 || lon > 180
44 @error = "Longitude #{lon} out of range"
45 render :action => "error"
47 @results = [{ :lat => lat, :lon => lon,
48 :zoom => params[:zoom],
49 :name => "#{lat}, #{lon}" }]
51 render :action => "results"
55 def search_us_postcode
56 # get query parameters
57 query = params[:query]
62 # ask geocoder.us (they have a non-commercial use api)
63 response = fetch_text("http://rpc.geocoder.us/service/csv?zip=#{escape_query(query)}")
66 unless response.match(/couldn't find this zip/)
67 data = response.split(/\s*,\s+/) # lat,long,town,state,zip
68 @results.push(:lat => data[0], :lon => data[1],
69 :zoom => POSTCODE_ZOOM,
70 :prefix => "#{data[2]}, #{data[3]},",
74 render :action => "results"
75 rescue StandardError => ex
76 @error = "Error contacting rpc.geocoder.us: #{ex}"
77 render :action => "error"
80 def search_uk_postcode
81 # get query parameters
82 query = params[:query]
87 # ask npemap.org.uk to do a combined npemap + freethepostcode search
88 response = fetch_text("http://www.npemap.org.uk/cgi/geocoder.fcgi?format=text&postcode=#{escape_query(query)}")
91 unless response.match(/Error/)
92 dataline = response.split(/\n/)[1]
93 data = dataline.split(/,/) # easting,northing,postcode,lat,long
94 postcode = data[2].gsub(/'/, "")
95 zoom = POSTCODE_ZOOM - postcode.count("#")
96 @results.push(:lat => data[3], :lon => data[4], :zoom => zoom,
100 render :action => "results"
101 rescue StandardError => ex
102 @error = "Error contacting www.npemap.org.uk: #{ex}"
103 render :action => "error"
106 def search_ca_postcode
107 # get query parameters
108 query = params[:query]
111 # ask geocoder.ca (note - they have a per-day limit)
112 response = fetch_xml("http://geocoder.ca/?geoit=XML&postal=#{escape_query(query)}")
115 if response.get_elements("geodata/error").empty?
116 @results.push(:lat => response.get_text("geodata/latt").to_s,
117 :lon => response.get_text("geodata/longt").to_s,
118 :zoom => POSTCODE_ZOOM,
119 :name => query.upcase)
122 render :action => "results"
123 rescue StandardError => ex
124 @error = "Error contacting geocoder.ca: #{ex}"
125 render :action => "error"
128 def search_osm_nominatim
129 # get query parameters
130 query = params[:query]
131 minlon = params[:minlon]
132 minlat = params[:minlat]
133 maxlon = params[:maxlon]
134 maxlat = params[:maxlat]
137 if minlon && minlat && maxlon && maxlat
138 viewbox = "&viewbox=#{minlon},#{maxlat},#{maxlon},#{minlat}"
141 # get objects to excude
142 exclude = "&exclude_place_ids=#{params[:exclude]}" if params[:exclude]
145 response = fetch_xml("http:#{NOMINATIM_URL}search?format=xml&q=#{escape_query(query)}#{viewbox}#{exclude}&accept-language=#{http_accept_language.user_preferred_languages.join(',')}")
147 # extract the results from the response
148 results = response.elements["searchresults"]
150 # extract parameters from more_url
151 more_url_params = CGI.parse(URI.parse(results.attributes["more_url"]).query)
153 # create result array
156 # create parameter hash for "more results" link
157 @more_params = params.merge(:exclude => more_url_params["exclude_place_ids"].first)
160 results.elements.each("place") do |place|
161 lat = place.attributes["lat"].to_s
162 lon = place.attributes["lon"].to_s
163 klass = place.attributes["class"].to_s
164 type = place.attributes["type"].to_s
165 name = place.attributes["display_name"].to_s
166 min_lat, max_lat, min_lon, max_lon = place.attributes["boundingbox"].to_s.split(",")
170 prefix_name = t "geocoder.search_osm_nominatim.prefix.#{klass}.#{type}", :default => type.gsub("_", " ").capitalize
172 if klass == "boundary" && type == "administrative"
173 rank = (place.attributes["place_rank"].to_i + 1) / 2
174 prefix_name = t "geocoder.search_osm_nominatim.admin_levels.level#{rank}", :default => prefix_name
176 prefix = t "geocoder.search_osm_nominatim.prefix_format", :name => prefix_name
177 object_type = place.attributes["osm_type"]
178 object_id = place.attributes["osm_id"]
180 @results.push(:lat => lat, :lon => lon,
181 :min_lat => min_lat, :max_lat => max_lat,
182 :min_lon => min_lon, :max_lon => max_lon,
183 :prefix => prefix, :name => name,
184 :type => object_type, :id => object_id)
187 render :action => "results"
188 rescue StandardError => ex
189 @error = "Error contacting nominatim.openstreetmap.org: #{ex}"
190 render :action => "error"
194 # get query parameters
195 query = params[:query]
197 # get preferred language
198 lang = I18n.locale.to_s.split("-").first
200 # create result array
204 response = fetch_xml("http://api.geonames.org/search?q=#{escape_query(query)}&lang=#{lang}&maxRows=20&username=#{GEONAMES_USERNAME}")
207 response.elements.each("geonames/geoname") do |geoname|
208 lat = geoname.get_text("lat").to_s
209 lon = geoname.get_text("lng").to_s
210 name = geoname.get_text("name").to_s
211 country = geoname.get_text("countryName").to_s
212 @results.push(:lat => lat, :lon => lon,
213 :zoom => GEONAMES_ZOOM,
215 :suffix => ", #{country}")
218 render :action => "results"
219 rescue StandardError => ex
220 @error = "Error contacting api.geonames.org: #{ex}"
221 render :action => "error"
224 def search_osm_nominatim_reverse
225 # get query parameters
230 # create result array
234 response = fetch_xml("http:#{NOMINATIM_URL}reverse?lat=#{lat}&lon=#{lon}&zoom=#{zoom}&accept-language=#{http_accept_language.user_preferred_languages.join(',')}")
237 response.elements.each("reversegeocode/result") do |result|
238 lat = result.attributes["lat"].to_s
239 lon = result.attributes["lon"].to_s
240 object_type = result.attributes["osm_type"]
241 object_id = result.attributes["osm_id"]
242 description = result.get_text.to_s
244 @results.push(:lat => lat, :lon => lon,
246 :name => description,
247 :type => object_type, :id => object_id)
250 render :action => "results"
251 rescue StandardError => ex
252 @error = "Error contacting nominatim.openstreetmap.org: #{ex}"
253 render :action => "error"
256 def search_geonames_reverse
257 # get query parameters
261 # get preferred language
262 lang = I18n.locale.to_s.split("-").first
264 # create result array
268 response = fetch_xml("http://api.geonames.org/countrySubdivision?lat=#{lat}&lng=#{lon}&lang=#{lang}&username=#{GEONAMES_USERNAME}")
271 response.elements.each("geonames/countrySubdivision") do |geoname|
272 name = geoname.get_text("adminName1").to_s
273 country = geoname.get_text("countryName").to_s
274 @results.push(:lat => lat, :lon => lon,
275 :zoom => GEONAMES_ZOOM,
277 :suffix => ", #{country}")
280 render :action => "results"
281 rescue StandardError => ex
282 @error = "Error contacting api.geonames.org: #{ex}"
283 render :action => "error"
289 OSM.http_client.get(URI.parse(url)).body
293 REXML::Document.new(fetch_text(url))
296 def escape_query(query)
297 URI.escape(query, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]", false, "N"))
301 query = params[:query]
306 if latlon = query.match(/^([NS])\s*(\d{1,3}(\.\d*)?)\W*([EW])\s*(\d{1,3}(\.\d*)?)$/).try(:captures) # [NSEW] decimal degrees
307 params.merge!(nsew_to_decdeg(latlon)).delete(:query)
308 elsif latlon = query.match(/^(\d{1,3}(\.\d*)?)\s*([NS])\W*(\d{1,3}(\.\d*)?)\s*([EW])$/).try(:captures) # decimal degrees [NSEW]
309 params.merge!(nsew_to_decdeg(latlon)).delete(:query)
311 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
312 params.merge!(ddm_to_decdeg(latlon)).delete(:query)
313 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]
314 params.merge!(ddm_to_decdeg(latlon)).delete(:query)
316 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
317 params.merge!(dms_to_decdeg(latlon)).delete(:query)
318 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]
319 params.merge!(dms_to_decdeg(latlon)).delete(:query)
321 elsif latlon = query.match(/^\s*([+-]?\d+(\.\d*)?)\s*[\s,]\s*([+-]?\d+(\.\d*)?)\s*$/)
322 params.merge!(:lat => latlon[1].to_f, :lon => latlon[3].to_f).delete(:query)
326 def nsew_to_decdeg(captures)
329 captures[2].downcase != "s" ? lat = captures[0].to_f : lat = -(captures[0].to_f)
330 captures[5].downcase != "w" ? lon = captures[3].to_f : lon = -(captures[3].to_f)
332 captures[0].downcase != "s" ? lat = captures[1].to_f : lat = -(captures[1].to_f)
333 captures[3].downcase != "w" ? lon = captures[4].to_f : lon = -(captures[4].to_f)
335 { :lat => lat, :lon => lon }
338 def ddm_to_decdeg(captures)
341 captures[3].downcase != "s" ? lat = captures[0].to_f + captures[1].to_f / 60 : lat = -(captures[0].to_f + captures[1].to_f / 60)
342 captures[7].downcase != "w" ? lon = captures[4].to_f + captures[5].to_f / 60 : lon = -(captures[4].to_f + captures[5].to_f / 60)
344 captures[0].downcase != "s" ? lat = captures[1].to_f + captures[2].to_f / 60 : lat = -(captures[1].to_f + captures[2].to_f / 60)
345 captures[4].downcase != "w" ? lon = captures[5].to_f + captures[6].to_f / 60 : lon = -(captures[5].to_f + captures[6].to_f / 60)
347 { :lat => lat, :lon => lon }
350 def dms_to_decdeg(captures)
353 captures[4].downcase != "s" ? lat = captures[0].to_f + (captures[1].to_f + captures[2].to_f / 60) / 60 : lat = -(captures[0].to_f + (captures[1].to_f + captures[2].to_f / 60) / 60)
354 captures[9].downcase != "w" ? lon = captures[5].to_f + (captures[6].to_f + captures[7].to_f / 60) / 60 : lon = -(captures[5].to_f + (captures[6].to_f + captures[7].to_f / 60) / 60)
356 captures[0].downcase != "s" ? lat = captures[1].to_f + (captures[2].to_f + captures[3].to_f / 60) / 60 : lat = -(captures[1].to_f + (captures[2].to_f + captures[3].to_f / 60) / 60)
357 captures[5].downcase != "w" ? lon = captures[6].to_f + (captures[7].to_f + captures[8].to_f / 60) / 60 : lon = -(captures[6].to_f + (captures[7].to_f + captures[8].to_f / 60) / 60)
359 { :lat => lat, :lon => lon }