3 class GeocoderController < ApplicationController
6 require 'rexml/document'
8 before_filter :authorize_web
9 before_filter :set_locale
10 before_filter :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 or lat > 90
41 @error = "Latitude #{lat} out of range"
42 render :action => "error"
43 elsif lon < -180 or 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 Exception => ex
76 @error = "Error contacting rpc.geocoder.us: #{ex.to_s}"
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 Exception => ex
102 @error = "Error contacting www.npemap.org.uk: #{ex.to_s}"
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 Exception => ex
124 @error = "Error contacting geocoder.ca: #{ex.to_s}"
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
143 exclude = "&exclude_place_ids=#{params[:exclude].join(',')}"
147 response = fetch_xml("#{NOMINATIM_URL}search?format=xml&q=#{escape_query(query)}#{viewbox}#{exclude}&accept-language=#{http_accept_language.user_preferred_languages.join(',')}")
149 # create result array
152 # create parameter hash for "more results" link
153 @more_params = params.reverse_merge({ :exclude => [] })
155 # extract the results from the response
156 results = response.elements["searchresults"]
159 results.elements.each("place") do |place|
160 lat = place.attributes["lat"].to_s
161 lon = place.attributes["lon"].to_s
162 klass = place.attributes["class"].to_s
163 type = place.attributes["type"].to_s
164 name = place.attributes["display_name"].to_s
165 min_lat,max_lat,min_lon,max_lon = place.attributes["boundingbox"].to_s.split(",")
169 prefix_name = t "geocoder.search_osm_nominatim.prefix.#{klass}.#{type}", :default => type.gsub("_", " ").capitalize
171 if klass == 'boundary' and type == 'administrative'
172 rank = (place.attributes["place_rank"].to_i + 1) / 2
173 prefix_name = t "geocoder.search_osm_nominatim.admin_levels.level#{rank}", :default => prefix_name
175 prefix = t "geocoder.search_osm_nominatim.prefix_format", :name => prefix_name
176 object_type = place.attributes["osm_type"]
177 object_id = place.attributes["osm_id"]
179 @results.push({:lat => lat, :lon => lon,
180 :min_lat => min_lat, :max_lat => max_lat,
181 :min_lon => min_lon, :max_lon => max_lon,
182 :prefix => prefix, :name => name,
183 :type => object_type, :id => object_id})
184 @more_params[:exclude].push(place.attributes["place_id"].to_s)
187 render :action => "results"
188 # rescue Exception => ex
189 # @error = "Error contacting nominatim.openstreetmap.org: #{ex.to_s}"
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 Exception => ex
220 @error = "Error contacting ws.geonames.org: #{ex.to_s}"
221 render :action => "error"
224 def search_osm_nominatim_reverse
225 # get query parameters
230 # create result array
234 response = fetch_xml("#{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 Exception => ex
252 @error = "Error contacting nominatim.openstreetmap.org: #{ex.to_s}"
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 Exception => ex
282 @error = "Error contacting ws.geonames.org: #{ex.to_s}"
283 render :action => "error"
289 return Net::HTTP.get(URI.parse(url))
293 return REXML::Document.new(fetch_text(url))
296 def format_distance(distance)
297 return t("geocoder.distance", :count => distance)
300 def format_direction(bearing)
301 return t("geocoder.direction.south_west") if bearing >= 22.5 and bearing < 67.5
302 return t("geocoder.direction.south") if bearing >= 67.5 and bearing < 112.5
303 return t("geocoder.direction.south_east") if bearing >= 112.5 and bearing < 157.5
304 return t("geocoder.direction.east") if bearing >= 157.5 and bearing < 202.5
305 return t("geocoder.direction.north_east") if bearing >= 202.5 and bearing < 247.5
306 return t("geocoder.direction.north") if bearing >= 247.5 and bearing < 292.5
307 return t("geocoder.direction.north_west") if bearing >= 292.5 and bearing < 337.5
308 return t("geocoder.direction.west")
311 def format_name(name)
312 return name.gsub(/( *\[[^\]]*\])*$/, "")
315 def count_results(results)
318 results.each do |source|
319 count += source[:results].length if source[:results]
325 def escape_query(query)
326 return URI.escape(query, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]", false, 'N'))
330 query = params[:query]
335 if latlon = query.match(/^([NS])\s*(\d{1,3}(\.\d*)?)\W*([EW])\s*(\d{1,3}(\.\d*)?)$/).try(:captures) # [NSEW] decimal degrees
336 params.merge!(nsew_to_decdeg(latlon)).delete(:query)
337 elsif latlon = query.match(/^(\d{1,3}(\.\d*)?)\s*([NS])\W*(\d{1,3}(\.\d*)?)\s*([EW])$/).try(:captures) # decimal degrees [NSEW]
338 params.merge!(nsew_to_decdeg(latlon)).delete(:query)
340 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
341 params.merge!(ddm_to_decdeg(latlon)).delete(:query)
342 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]
343 params.merge!(ddm_to_decdeg(latlon)).delete(:query)
345 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
346 params.merge!(dms_to_decdeg(latlon)).delete(:query)
347 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]
348 params.merge!(dms_to_decdeg(latlon)).delete(:query)
350 elsif latlon = query.match(/^\s*([+-]?\d+(\.\d*)?)\s*[\s,]\s*([+-]?\d+(\.\d*)?)\s*$/)
351 params.merge!({:lat => latlon[1].to_f, :lon => latlon[3].to_f}).delete(:query)
355 def nsew_to_decdeg(captures)
358 captures[2].downcase != 's' ? lat = captures[0].to_f : lat = -(captures[0].to_f)
359 captures[5].downcase != 'w' ? lon = captures[3].to_f : lon = -(captures[3].to_f)
361 captures[0].downcase != 's' ? lat = captures[1].to_f : lat = -(captures[1].to_f)
362 captures[3].downcase != 'w' ? lon = captures[4].to_f : lon = -(captures[4].to_f)
364 {:lat => lat, :lon => lon}
367 def ddm_to_decdeg(captures)
370 captures[3].downcase != 's' ? lat = captures[0].to_f + captures[1].to_f/60 : lat = -(captures[0].to_f + captures[1].to_f/60)
371 captures[7].downcase != 'w' ? lon = captures[4].to_f + captures[5].to_f/60 : lon = -(captures[4].to_f + captures[5].to_f/60)
373 captures[0].downcase != 's' ? lat = captures[1].to_f + captures[2].to_f/60 : lat = -(captures[1].to_f + captures[2].to_f/60)
374 captures[4].downcase != 'w' ? lon = captures[5].to_f + captures[6].to_f/60 : lon = -(captures[5].to_f + captures[6].to_f/60)
376 {:lat => lat, :lon => lon}
379 def dms_to_decdeg(captures)
382 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)
383 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)
385 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)
386 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)
388 {:lat => lat, :lon => lon}