3 class GeocoderController < ApplicationController
7 require 'rexml/document'
9 before_filter :authorize_web
10 before_filter :set_locale
11 before_filter :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)
21 elsif params[:query].match(/^\d{5}(-\d{4})?$/)
22 @sources.push "us_postcode"
23 @sources.push "osm_nominatim"
24 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)
25 @sources.push "uk_postcode"
26 @sources.push "osm_nominatim"
27 elsif params[:query].match(/^[A-Z]\d[A-Z]\s*\d[A-Z]\d$/i)
28 @sources.push "ca_postcode"
29 @sources.push "osm_nominatim"
31 @sources.push "osm_nominatim"
32 @sources.push "geonames" if defined?(GEONAMES_USERNAME)
35 render :layout => map_layout
39 lat = params[:lat].to_f
40 lon = params[:lon].to_f
41 if lat < -90 || lat > 90
42 @error = "Latitude #{lat} out of range"
43 render :action => "error"
44 elsif lon < -180 || lon > 180
45 @error = "Longitude #{lon} out of range"
46 render :action => "error"
48 @results = [{ :lat => lat, :lon => lon,
49 :zoom => params[:zoom],
50 :name => "#{lat}, #{lon}" }]
52 render :action => "results"
56 def search_us_postcode
57 # get query parameters
58 query = params[:query]
63 # ask geocoder.us (they have a non-commercial use api)
64 response = fetch_text("http://rpc.geocoder.us/service/csv?zip=#{escape_query(query)}")
67 unless response.match(/couldn't find this zip/)
68 data = response.split(/\s*,\s+/) # lat,long,town,state,zip
69 @results.push(:lat => data[0], :lon => data[1],
70 :zoom => POSTCODE_ZOOM,
71 :prefix => "#{data[2]}, #{data[3]},",
75 render :action => "results"
76 rescue StandardError => ex
77 @error = "Error contacting rpc.geocoder.us: #{ex}"
78 render :action => "error"
81 def search_uk_postcode
82 # get query parameters
83 query = params[:query]
88 # ask npemap.org.uk to do a combined npemap + freethepostcode search
89 response = fetch_text("http://www.npemap.org.uk/cgi/geocoder.fcgi?format=text&postcode=#{escape_query(query)}")
92 unless response.match(/Error/)
93 dataline = response.split(/\n/)[1]
94 data = dataline.split(/,/) # easting,northing,postcode,lat,long
95 postcode = data[2].gsub(/'/, "")
96 zoom = POSTCODE_ZOOM - postcode.count("#")
97 @results.push(:lat => data[3], :lon => data[4], :zoom => zoom,
101 render :action => "results"
102 rescue StandardError => ex
103 @error = "Error contacting www.npemap.org.uk: #{ex}"
104 render :action => "error"
107 def search_ca_postcode
108 # get query parameters
109 query = params[:query]
112 # ask geocoder.ca (note - they have a per-day limit)
113 response = fetch_xml("http://geocoder.ca/?geoit=XML&postal=#{escape_query(query)}")
116 if response.get_elements("geodata/error").empty?
117 @results.push(:lat => response.get_text("geodata/latt").to_s,
118 :lon => response.get_text("geodata/longt").to_s,
119 :zoom => POSTCODE_ZOOM,
120 :name => query.upcase)
123 render :action => "results"
124 rescue StandardError => ex
125 @error = "Error contacting geocoder.ca: #{ex}"
126 render :action => "error"
129 def search_osm_nominatim
130 # get query parameters
131 query = params[:query]
132 minlon = params[:minlon]
133 minlat = params[:minlat]
134 maxlon = params[:maxlon]
135 maxlat = params[:maxlat]
138 if minlon && minlat && maxlon && maxlat
139 viewbox = "&viewbox=#{minlon},#{maxlat},#{maxlon},#{minlat}"
142 # get objects to excude
144 exclude = "&exclude_place_ids=#{params[:exclude]}"
148 response = fetch_xml("http:#{NOMINATIM_URL}search?format=xml&q=#{escape_query(query)}#{viewbox}#{exclude}&accept-language=#{http_accept_language.user_preferred_languages.join(',')}")
150 # extract the results from the response
151 results = response.elements["searchresults"]
153 # extract parameters from more_url
154 more_url_params = CGI.parse(URI.parse(results.attributes["more_url"]).query)
156 # create result array
159 # create parameter hash for "more results" link
160 @more_params = params.merge(:exclude => more_url_params["exclude_place_ids"].first)
163 results.elements.each("place") do |place|
164 lat = place.attributes["lat"].to_s
165 lon = place.attributes["lon"].to_s
166 klass = place.attributes["class"].to_s
167 type = place.attributes["type"].to_s
168 name = place.attributes["display_name"].to_s
169 min_lat, max_lat, min_lon, max_lon = place.attributes["boundingbox"].to_s.split(",")
173 prefix_name = t "geocoder.search_osm_nominatim.prefix.#{klass}.#{type}", :default => type.gsub("_", " ").capitalize
175 if klass == 'boundary' && type == 'administrative'
176 rank = (place.attributes["place_rank"].to_i + 1) / 2
177 prefix_name = t "geocoder.search_osm_nominatim.admin_levels.level#{rank}", :default => prefix_name
179 prefix = t "geocoder.search_osm_nominatim.prefix_format", :name => prefix_name
180 object_type = place.attributes["osm_type"]
181 object_id = place.attributes["osm_id"]
183 @results.push(:lat => lat, :lon => lon,
184 :min_lat => min_lat, :max_lat => max_lat,
185 :min_lon => min_lon, :max_lon => max_lon,
186 :prefix => prefix, :name => name,
187 :type => object_type, :id => object_id)
190 render :action => "results"
191 # rescue StandardError => ex
192 # @error = "Error contacting nominatim.openstreetmap.org: #{ex.to_s}"
193 # render :action => "error"
197 # get query parameters
198 query = params[:query]
200 # get preferred language
201 lang = I18n.locale.to_s.split("-").first
203 # create result array
207 response = fetch_xml("http://api.geonames.org/search?q=#{escape_query(query)}&lang=#{lang}&maxRows=20&username=#{GEONAMES_USERNAME}")
210 response.elements.each("geonames/geoname") do |geoname|
211 lat = geoname.get_text("lat").to_s
212 lon = geoname.get_text("lng").to_s
213 name = geoname.get_text("name").to_s
214 country = geoname.get_text("countryName").to_s
215 @results.push(:lat => lat, :lon => lon,
216 :zoom => GEONAMES_ZOOM,
218 :suffix => ", #{country}")
221 render :action => "results"
222 rescue StandardError => ex
223 @error = "Error contacting ws.geonames.org: #{ex}"
224 render :action => "error"
227 def search_osm_nominatim_reverse
228 # get query parameters
233 # create result array
237 response = fetch_xml("http:#{NOMINATIM_URL}reverse?lat=#{lat}&lon=#{lon}&zoom=#{zoom}&accept-language=#{http_accept_language.user_preferred_languages.join(',')}")
240 response.elements.each("reversegeocode/result") do |result|
241 lat = result.attributes["lat"].to_s
242 lon = result.attributes["lon"].to_s
243 object_type = result.attributes["osm_type"]
244 object_id = result.attributes["osm_id"]
245 description = result.get_text.to_s
247 @results.push(:lat => lat, :lon => lon,
249 :name => description,
250 :type => object_type, :id => object_id)
253 render :action => "results"
254 rescue StandardError => ex
255 @error = "Error contacting nominatim.openstreetmap.org: #{ex}"
256 render :action => "error"
259 def search_geonames_reverse
260 # get query parameters
264 # get preferred language
265 lang = I18n.locale.to_s.split("-").first
267 # create result array
271 response = fetch_xml("http://api.geonames.org/countrySubdivision?lat=#{lat}&lng=#{lon}&lang=#{lang}&username=#{GEONAMES_USERNAME}")
274 response.elements.each("geonames/countrySubdivision") do |geoname|
275 name = geoname.get_text("adminName1").to_s
276 country = geoname.get_text("countryName").to_s
277 @results.push(:lat => lat, :lon => lon,
278 :zoom => GEONAMES_ZOOM,
280 :suffix => ", #{country}")
283 render :action => "results"
284 rescue StandardError => ex
285 @error = "Error contacting ws.geonames.org: #{ex}"
286 render :action => "error"
292 Net::HTTP.get(URI.parse(url))
296 REXML::Document.new(fetch_text(url))
299 def format_distance(distance)
300 t("geocoder.distance", :count => distance)
303 def format_direction(bearing)
304 return t("geocoder.direction.south_west") if bearing >= 22.5 && bearing < 67.5
305 return t("geocoder.direction.south") if bearing >= 67.5 && bearing < 112.5
306 return t("geocoder.direction.south_east") if bearing >= 112.5 && bearing < 157.5
307 return t("geocoder.direction.east") if bearing >= 157.5 && bearing < 202.5
308 return t("geocoder.direction.north_east") if bearing >= 202.5 && bearing < 247.5
309 return t("geocoder.direction.north") if bearing >= 247.5 && bearing < 292.5
310 return t("geocoder.direction.north_west") if bearing >= 292.5 && bearing < 337.5
311 t("geocoder.direction.west")
314 def format_name(name)
315 name.gsub(/( *\[[^\]]*\])*$/, "")
318 def count_results(results)
321 results.each do |source|
322 count += source[:results].length if source[:results]
328 def escape_query(query)
329 URI.escape(query, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]", false, 'N'))
333 query = params[:query]
338 if latlon = query.match(/^([NS])\s*(\d{1,3}(\.\d*)?)\W*([EW])\s*(\d{1,3}(\.\d*)?)$/).try(:captures) # [NSEW] decimal degrees
339 params.merge!(nsew_to_decdeg(latlon)).delete(:query)
340 elsif latlon = query.match(/^(\d{1,3}(\.\d*)?)\s*([NS])\W*(\d{1,3}(\.\d*)?)\s*([EW])$/).try(:captures) # decimal degrees [NSEW]
341 params.merge!(nsew_to_decdeg(latlon)).delete(:query)
343 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
344 params.merge!(ddm_to_decdeg(latlon)).delete(:query)
345 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]
346 params.merge!(ddm_to_decdeg(latlon)).delete(:query)
348 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
349 params.merge!(dms_to_decdeg(latlon)).delete(:query)
350 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]
351 params.merge!(dms_to_decdeg(latlon)).delete(:query)
353 elsif latlon = query.match(/^\s*([+-]?\d+(\.\d*)?)\s*[\s,]\s*([+-]?\d+(\.\d*)?)\s*$/)
354 params.merge!(:lat => latlon[1].to_f, :lon => latlon[3].to_f).delete(:query)
358 def nsew_to_decdeg(captures)
361 captures[2].downcase != 's' ? lat = captures[0].to_f : lat = -(captures[0].to_f)
362 captures[5].downcase != 'w' ? lon = captures[3].to_f : lon = -(captures[3].to_f)
364 captures[0].downcase != 's' ? lat = captures[1].to_f : lat = -(captures[1].to_f)
365 captures[3].downcase != 'w' ? lon = captures[4].to_f : lon = -(captures[4].to_f)
367 { :lat => lat, :lon => lon }
370 def ddm_to_decdeg(captures)
373 captures[3].downcase != 's' ? lat = captures[0].to_f + captures[1].to_f / 60 : lat = -(captures[0].to_f + captures[1].to_f / 60)
374 captures[7].downcase != 'w' ? lon = captures[4].to_f + captures[5].to_f / 60 : lon = -(captures[4].to_f + captures[5].to_f / 60)
376 captures[0].downcase != 's' ? lat = captures[1].to_f + captures[2].to_f / 60 : lat = -(captures[1].to_f + captures[2].to_f / 60)
377 captures[4].downcase != 'w' ? lon = captures[5].to_f + captures[6].to_f / 60 : lon = -(captures[5].to_f + captures[6].to_f / 60)
379 { :lat => lat, :lon => lon }
382 def dms_to_decdeg(captures)
385 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)
386 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)
388 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)
389 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)
391 { :lat => lat, :lon => lon }