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"
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 # create result array
201 response = fetch_xml("http://api.geonames.org/search?q=#{escape_query(query)}&maxRows=20&username=#{GEONAMES_USERNAME}")
204 response.elements.each("geonames/geoname") do |geoname|
205 lat = geoname.get_text("lat").to_s
206 lon = geoname.get_text("lng").to_s
207 name = geoname.get_text("name").to_s
208 country = geoname.get_text("countryName").to_s
209 @results.push({:lat => lat, :lon => lon,
210 :zoom => GEONAMES_ZOOM,
212 :suffix => ", #{country}"})
215 render :action => "results"
216 rescue Exception => ex
217 @error = "Error contacting ws.geonames.org: #{ex.to_s}"
218 render :action => "error"
221 def search_osm_nominatim_reverse
222 # get query parameters
227 # create result array
231 response = fetch_xml("#{NOMINATIM_URL}reverse?lat=#{lat}&lon=#{lon}&zoom=#{zoom}&accept-language=#{http_accept_language.user_preferred_languages.join(',')}")
234 response.elements.each("reversegeocode/result") do |result|
235 lat = result.attributes["lat"].to_s
236 lon = result.attributes["lon"].to_s
237 object_type = result.attributes["osm_type"]
238 object_id = result.attributes["osm_id"]
239 description = result.get_text.to_s
241 @results.push({:lat => lat, :lon => lon,
243 :name => description,
244 :type => object_type, :id => object_id})
247 render :action => "results"
248 rescue Exception => ex
249 @error = "Error contacting nominatim.openstreetmap.org: #{ex.to_s}"
250 render :action => "error"
253 def search_geonames_reverse
254 # get query parameters
258 # create result array
262 response = fetch_xml("http://ws.geonames.org/countrySubdivision?lat=#{lat}&lng=#{lon}")
265 response.elements.each("geonames/countrySubdivision") do |geoname|
266 name = geoname.get_text("adminName1").to_s
267 country = geoname.get_text("countryName").to_s
268 @results.push({:lat => lat, :lon => lon,
269 :zoom => GEONAMES_ZOOM,
271 :suffix => ", #{country}"})
274 render :action => "results"
275 rescue Exception => ex
276 @error = "Error contacting ws.geonames.org: #{ex.to_s}"
277 render :action => "error"
283 return Net::HTTP.get(URI.parse(url))
287 return REXML::Document.new(fetch_text(url))
290 def format_distance(distance)
291 return t("geocoder.distance", :count => distance)
294 def format_direction(bearing)
295 return t("geocoder.direction.south_west") if bearing >= 22.5 and bearing < 67.5
296 return t("geocoder.direction.south") if bearing >= 67.5 and bearing < 112.5
297 return t("geocoder.direction.south_east") if bearing >= 112.5 and bearing < 157.5
298 return t("geocoder.direction.east") if bearing >= 157.5 and bearing < 202.5
299 return t("geocoder.direction.north_east") if bearing >= 202.5 and bearing < 247.5
300 return t("geocoder.direction.north") if bearing >= 247.5 and bearing < 292.5
301 return t("geocoder.direction.north_west") if bearing >= 292.5 and bearing < 337.5
302 return t("geocoder.direction.west")
305 def format_name(name)
306 return name.gsub(/( *\[[^\]]*\])*$/, "")
309 def count_results(results)
312 results.each do |source|
313 count += source[:results].length if source[:results]
319 def escape_query(query)
320 return URI.escape(query, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]", false, 'N'))
324 query = params[:query]
329 if latlon = query.match(/^([NS])\s*(\d{1,3}(\.\d*)?)\W*([EW])\s*(\d{1,3}(\.\d*)?)$/).try(:captures) # [NSEW] decimal degrees
330 params.merge!(nsew_to_decdeg(latlon)).delete(:query)
331 elsif latlon = query.match(/^(\d{1,3}(\.\d*)?)\s*([NS])\W*(\d{1,3}(\.\d*)?)\s*([EW])$/).try(:captures) # decimal degrees [NSEW]
332 params.merge!(nsew_to_decdeg(latlon)).delete(:query)
334 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
335 params.merge!(ddm_to_decdeg(latlon)).delete(:query)
336 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]
337 params.merge!(ddm_to_decdeg(latlon)).delete(:query)
339 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
340 params.merge!(dms_to_decdeg(latlon)).delete(:query)
341 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]
342 params.merge!(dms_to_decdeg(latlon)).delete(:query)
344 elsif latlon = query.match(/^\s*([+-]?\d+(\.\d*)?)\s*[\s,]\s*([+-]?\d+(\.\d*)?)\s*$/)
345 params.merge!({:lat => latlon[1].to_f, :lon => latlon[3].to_f}).delete(:query)
349 def nsew_to_decdeg(captures)
352 captures[2].downcase != 's' ? lat = captures[0].to_f : lat = -(captures[0].to_f)
353 captures[5].downcase != 'w' ? lon = captures[3].to_f : lon = -(captures[3].to_f)
355 captures[0].downcase != 's' ? lat = captures[1].to_f : lat = -(captures[1].to_f)
356 captures[3].downcase != 'w' ? lon = captures[4].to_f : lon = -(captures[4].to_f)
358 {:lat => lat, :lon => lon}
361 def ddm_to_decdeg(captures)
364 captures[3].downcase != 's' ? lat = captures[0].to_f + captures[1].to_f/60 : lat = -(captures[0].to_f + captures[1].to_f/60)
365 captures[7].downcase != 'w' ? lon = captures[4].to_f + captures[5].to_f/60 : lon = -(captures[4].to_f + captures[5].to_f/60)
367 captures[0].downcase != 's' ? lat = captures[1].to_f + captures[2].to_f/60 : lat = -(captures[1].to_f + captures[2].to_f/60)
368 captures[4].downcase != 'w' ? lon = captures[5].to_f + captures[6].to_f/60 : lon = -(captures[5].to_f + captures[6].to_f/60)
370 {:lat => lat, :lon => lon}
373 def dms_to_decdeg(captures)
376 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)
377 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)
379 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)
380 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)
382 {:lat => lat, :lon => lon}