3 class GeocoderController < ApplicationController
6 require 'rexml/document'
8 before_filter :authorize_web
9 before_filter :set_locale
10 before_filter :convert_latlon, :only => [:search]
13 @query = params[:query]
16 @query.sub(/^\s+/, "")
17 @query.sub(/\s+$/, "")
19 if @query.match(/^[+-]?\d+(\.\d*)?\s*[\s,]\s*[+-]?\d+(\.\d*)?$/)
20 @sources.push "latlon"
21 elsif @query.match(/^\d{5}(-\d{4})?$/)
22 @sources.push "us_postcode"
23 @sources.push "osm_nominatim"
24 elsif @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 @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)
37 # get query parameters
38 query = params[:query]
44 if m = query.match(/^\s*([+-]?\d+(\.\d*)?)\s*[\s,]\s*([+-]?\d+(\.\d*)?)\s*$/)
50 if lat < -90 or lat > 90
51 @error = "Latitude #{lat} out of range"
52 render :action => "error"
53 elsif lon < -180 or lon > 180
54 @error = "Longitude #{lon} out of range"
55 render :action => "error"
57 @results.push({:lat => lat, :lon => lon,
58 :zoom => POSTCODE_ZOOM,
59 :name => "#{lat}, #{lon}"})
61 render :action => "results"
65 def search_us_postcode
66 # get query parameters
67 query = params[:query]
72 # ask geocoder.us (they have a non-commercial use api)
73 response = fetch_text("http://rpc.geocoder.us/service/csv?zip=#{escape_query(query)}")
76 unless response.match(/couldn't find this zip/)
77 data = response.split(/\s*,\s+/) # lat,long,town,state,zip
78 @results.push({:lat => data[0], :lon => data[1],
79 :zoom => POSTCODE_ZOOM,
80 :prefix => "#{data[2]}, #{data[3]},",
84 render :action => "results"
85 rescue Exception => ex
86 @error = "Error contacting rpc.geocoder.us: #{ex.to_s}"
87 render :action => "error"
90 def search_uk_postcode
91 # get query parameters
92 query = params[:query]
97 # ask npemap.org.uk to do a combined npemap + freethepostcode search
98 response = fetch_text("http://www.npemap.org.uk/cgi/geocoder.fcgi?format=text&postcode=#{escape_query(query)}")
101 unless response.match(/Error/)
102 dataline = response.split(/\n/)[1]
103 data = dataline.split(/,/) # easting,northing,postcode,lat,long
104 postcode = data[2].gsub(/'/, "")
105 zoom = POSTCODE_ZOOM - postcode.count("#")
106 @results.push({:lat => data[3], :lon => data[4], :zoom => zoom,
110 render :action => "results"
111 rescue Exception => ex
112 @error = "Error contacting www.npemap.org.uk: #{ex.to_s}"
113 render :action => "error"
116 def search_ca_postcode
117 # get query parameters
118 query = params[:query]
121 # ask geocoder.ca (note - they have a per-day limit)
122 response = fetch_xml("http://geocoder.ca/?geoit=XML&postal=#{escape_query(query)}")
125 if response.get_elements("geodata/error").empty?
126 @results.push({:lat => response.get_text("geodata/latt").to_s,
127 :lon => response.get_text("geodata/longt").to_s,
128 :zoom => POSTCODE_ZOOM,
129 :name => query.upcase})
132 render :action => "results"
133 rescue Exception => ex
134 @error = "Error contacting geocoder.ca: #{ex.to_s}"
135 render :action => "error"
138 def search_osm_nominatim
139 # get query parameters
140 query = params[:query]
141 minlon = params[:minlon]
142 minlat = params[:minlat]
143 maxlon = params[:maxlon]
144 maxlat = params[:maxlat]
147 if minlon && minlat && maxlon && maxlat
148 viewbox = "&viewbox=#{minlon},#{maxlat},#{maxlon},#{minlat}"
151 # get objects to excude
153 exclude = "&exclude_place_ids=#{params[:exclude].join(',')}"
157 response = fetch_xml("#{NOMINATIM_URL}search?format=xml&q=#{escape_query(query)}#{viewbox}#{exclude}&accept-language=#{request.user_preferred_languages.join(',')}")
159 # create result array
162 # create parameter hash for "more results" link
163 @more_params = params.reverse_merge({ :exclude => [] })
165 # extract the results from the response
166 results = response.elements["searchresults"]
169 results.elements.each("place") do |place|
170 lat = place.attributes["lat"].to_s
171 lon = place.attributes["lon"].to_s
172 klass = place.attributes["class"].to_s
173 type = place.attributes["type"].to_s
174 name = place.attributes["display_name"].to_s
175 min_lat,max_lat,min_lon,max_lon = place.attributes["boundingbox"].to_s.split(",")
176 prefix_name = t "geocoder.search_osm_nominatim.prefix.#{klass}.#{type}", :default => type.gsub("_", " ").capitalize
177 prefix = t "geocoder.search_osm_nominatim.prefix_format", :name => prefix_name
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 @more_params[:exclude].push(place.attributes["place_id"].to_s)
186 render :action => "results"
187 # rescue Exception => ex
188 # @error = "Error contacting nominatim.openstreetmap.org: #{ex.to_s}"
189 # render :action => "error"
193 # get query parameters
194 query = params[:query]
196 # create result array
200 response = fetch_xml("http://api.geonames.org/search?q=#{escape_query(query)}&maxRows=20&username=#{GEONAMES_USERNAME}")
203 response.elements.each("geonames/geoname") do |geoname|
204 lat = geoname.get_text("lat").to_s
205 lon = geoname.get_text("lng").to_s
206 name = geoname.get_text("name").to_s
207 country = geoname.get_text("countryName").to_s
208 @results.push({:lat => lat, :lon => lon,
209 :zoom => GEONAMES_ZOOM,
211 :suffix => ", #{country}"})
214 render :action => "results"
215 rescue Exception => ex
216 @error = "Error contacting ws.geonames.org: #{ex.to_s}"
217 render :action => "error"
223 @sources.push({ :name => "osm_nominatim" })
224 @sources.push({ :name => "geonames" })
227 def description_osm_nominatim
228 # get query parameters
233 # create result array
237 response = fetch_xml("#{NOMINATIM_URL}reverse?lat=#{lat}&lon=#{lon}&zoom=#{zoom}&accept-language=#{request.user_preferred_languages.join(',')}")
240 response.elements.each("reversegeocode/result") do |result|
241 description = result.get_text.to_s
243 @results.push({:prefix => "#{description}"})
246 render :action => "results"
247 rescue Exception => ex
248 @error = "Error contacting nominatim.openstreetmap.org: #{ex.to_s}"
249 render :action => "error"
252 def description_geonames
253 # get query parameters
257 # create result array
261 response = fetch_xml("http://ws.geonames.org/countrySubdivision?lat=#{lat}&lng=#{lon}")
264 response.elements.each("geonames/countrySubdivision") do |geoname|
265 name = geoname.get_text("adminName1").to_s
266 country = geoname.get_text("countryName").to_s
267 @results.push({:prefix => "#{name}, #{country}"})
270 render :action => "results"
271 rescue Exception => ex
272 @error = "Error contacting ws.geonames.org: #{ex.to_s}"
273 render :action => "error"
279 return Net::HTTP.get(URI.parse(url))
283 return REXML::Document.new(fetch_text(url))
286 def format_distance(distance)
287 return t("geocoder.distance", :count => distance)
290 def format_direction(bearing)
291 return t("geocoder.direction.south_west") if bearing >= 22.5 and bearing < 67.5
292 return t("geocoder.direction.south") if bearing >= 67.5 and bearing < 112.5
293 return t("geocoder.direction.south_east") if bearing >= 112.5 and bearing < 157.5
294 return t("geocoder.direction.east") if bearing >= 157.5 and bearing < 202.5
295 return t("geocoder.direction.north_east") if bearing >= 202.5 and bearing < 247.5
296 return t("geocoder.direction.north") if bearing >= 247.5 and bearing < 292.5
297 return t("geocoder.direction.north_west") if bearing >= 292.5 and bearing < 337.5
298 return t("geocoder.direction.west")
301 def format_name(name)
302 return name.gsub(/( *\[[^\]]*\])*$/, "")
305 def count_results(results)
308 results.each do |source|
309 count += source[:results].length if source[:results]
315 def escape_query(query)
316 return URI.escape(query, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]", false, 'N'))
320 @query = params[:query]
322 if latlon = @query.match(/^([NS])\s*(\d{1,3}(\.\d*)?)\W*([EW])\s*(\d{1,3}(\.\d*)?)$/).try(:captures) # [NSEW] decimal degrees
323 params[:query] = nsew_to_decdeg(latlon)
324 elsif latlon = @query.match(/^(\d{1,3}(\.\d*)?)\s*([NS])\W*(\d{1,3}(\.\d*)?)\s*([EW])$/).try(:captures) # decimal degrees [NSEW]
325 params[:query] = nsew_to_decdeg(latlon)
327 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
328 params[:query] = ddm_to_decdeg(latlon)
329 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]
330 params[:query] = ddm_to_decdeg(latlon)
332 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
333 params[:query] = dms_to_decdeg(latlon)
334 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]
335 params[:query] = dms_to_decdeg(latlon)
341 def nsew_to_decdeg(captures)
344 captures[1].downcase != 's' ? lat = captures[0].to_f : lat = -(captures[0].to_f)
345 captures[4].downcase != 'w' ? lon = captures[3].to_f : lon = -(captures[3].to_f)
347 captures[0].downcase != 's' ? lat = captures[1].to_f : lat = -(captures[1].to_f)
348 captures[3].downcase != 'w' ? lon = captures[4].to_f : lon = -(captures[4].to_f)
350 return "#{lat}, #{lon}"
353 def ddm_to_decdeg(captures)
356 captures[3].downcase != 's' ? lat = captures[0].to_f + captures[1].to_f/60 : lat = -(captures[0].to_f + captures[1].to_f/60)
357 captures[7].downcase != 'w' ? lon = captures[4].to_f + captures[5].to_f/60 : lon = -(captures[4].to_f + captures[5].to_f/60)
359 captures[0].downcase != 's' ? lat = captures[1].to_f + captures[2].to_f/60 : lat = -(captures[1].to_f + captures[2].to_f/60)
360 captures[4].downcase != 'w' ? lon = captures[5].to_f + captures[6].to_f/60 : lon = -(captures[5].to_f + captures[6].to_f/60)
362 return "#{lat}, #{lon}"
365 def dms_to_decdeg(captures)
368 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)
369 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)
371 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)
372 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)
374 return "#{lat}, #{lon}"