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
178 object_type = place.attributes["osm_type"]
179 object_id = place.attributes["osm_id"]
181 @results.push({:lat => lat, :lon => lon,
182 :min_lat => min_lat, :max_lat => max_lat,
183 :min_lon => min_lon, :max_lon => max_lon,
184 :prefix => prefix, :name => name,
185 :type => object_type, :id => object_id})
186 @more_params[:exclude].push(place.attributes["place_id"].to_s)
189 render :action => "results"
190 # rescue Exception => ex
191 # @error = "Error contacting nominatim.openstreetmap.org: #{ex.to_s}"
192 # render :action => "error"
196 # get query parameters
197 query = params[:query]
199 # create result array
203 response = fetch_xml("http://api.geonames.org/search?q=#{escape_query(query)}&maxRows=20&username=#{GEONAMES_USERNAME}")
206 response.elements.each("geonames/geoname") do |geoname|
207 lat = geoname.get_text("lat").to_s
208 lon = geoname.get_text("lng").to_s
209 name = geoname.get_text("name").to_s
210 country = geoname.get_text("countryName").to_s
211 @results.push({:lat => lat, :lon => lon,
212 :zoom => GEONAMES_ZOOM,
214 :suffix => ", #{country}"})
217 render :action => "results"
218 rescue Exception => ex
219 @error = "Error contacting ws.geonames.org: #{ex.to_s}"
220 render :action => "error"
226 @sources.push({ :name => "osm_nominatim" })
227 @sources.push({ :name => "geonames" })
230 def description_osm_nominatim
231 # get query parameters
236 # create result array
240 response = fetch_xml("#{NOMINATIM_URL}reverse?lat=#{lat}&lon=#{lon}&zoom=#{zoom}&accept-language=#{request.user_preferred_languages.join(',')}")
243 response.elements.each("reversegeocode/result") do |result|
244 description = result.get_text.to_s
246 @results.push({:prefix => "#{description}"})
249 render :action => "results"
250 rescue Exception => ex
251 @error = "Error contacting nominatim.openstreetmap.org: #{ex.to_s}"
252 render :action => "error"
255 def description_geonames
256 # get query parameters
260 # create result array
264 response = fetch_xml("http://ws.geonames.org/countrySubdivision?lat=#{lat}&lng=#{lon}")
267 response.elements.each("geonames/countrySubdivision") do |geoname|
268 name = geoname.get_text("adminName1").to_s
269 country = geoname.get_text("countryName").to_s
270 @results.push({:prefix => "#{name}, #{country}"})
273 render :action => "results"
274 rescue Exception => ex
275 @error = "Error contacting ws.geonames.org: #{ex.to_s}"
276 render :action => "error"
282 return Net::HTTP.get(URI.parse(url))
286 return REXML::Document.new(fetch_text(url))
289 def format_distance(distance)
290 return t("geocoder.distance", :count => distance)
293 def format_direction(bearing)
294 return t("geocoder.direction.south_west") if bearing >= 22.5 and bearing < 67.5
295 return t("geocoder.direction.south") if bearing >= 67.5 and bearing < 112.5
296 return t("geocoder.direction.south_east") if bearing >= 112.5 and bearing < 157.5
297 return t("geocoder.direction.east") if bearing >= 157.5 and bearing < 202.5
298 return t("geocoder.direction.north_east") if bearing >= 202.5 and bearing < 247.5
299 return t("geocoder.direction.north") if bearing >= 247.5 and bearing < 292.5
300 return t("geocoder.direction.north_west") if bearing >= 292.5 and bearing < 337.5
301 return t("geocoder.direction.west")
304 def format_name(name)
305 return name.gsub(/( *\[[^\]]*\])*$/, "")
308 def count_results(results)
311 results.each do |source|
312 count += source[:results].length if source[:results]
318 def escape_query(query)
319 return URI.escape(query, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]", false, 'N'))
323 @query = params[:query]
325 if latlon = @query.match(/^([NS])\s*(\d{1,3}(\.\d*)?)\W*([EW])\s*(\d{1,3}(\.\d*)?)$/).try(:captures) # [NSEW] decimal degrees
326 params[:query] = nsew_to_decdeg(latlon)
327 elsif latlon = @query.match(/^(\d{1,3}(\.\d*)?)\s*([NS])\W*(\d{1,3}(\.\d*)?)\s*([EW])$/).try(:captures) # decimal degrees [NSEW]
328 params[:query] = nsew_to_decdeg(latlon)
330 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
331 params[:query] = ddm_to_decdeg(latlon)
332 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]
333 params[:query] = ddm_to_decdeg(latlon)
335 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
336 params[:query] = dms_to_decdeg(latlon)
337 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]
338 params[:query] = dms_to_decdeg(latlon)
344 def nsew_to_decdeg(captures)
347 captures[2].downcase != 's' ? lat = captures[0].to_f : lat = -(captures[0].to_f)
348 captures[5].downcase != 'w' ? lon = captures[3].to_f : lon = -(captures[3].to_f)
350 captures[0].downcase != 's' ? lat = captures[1].to_f : lat = -(captures[1].to_f)
351 captures[3].downcase != 'w' ? lon = captures[4].to_f : lon = -(captures[4].to_f)
353 return "#{lat}, #{lon}"
356 def ddm_to_decdeg(captures)
359 captures[3].downcase != 's' ? lat = captures[0].to_f + captures[1].to_f/60 : lat = -(captures[0].to_f + captures[1].to_f/60)
360 captures[7].downcase != 'w' ? lon = captures[4].to_f + captures[5].to_f/60 : lon = -(captures[4].to_f + captures[5].to_f/60)
362 captures[0].downcase != 's' ? lat = captures[1].to_f + captures[2].to_f/60 : lat = -(captures[1].to_f + captures[2].to_f/60)
363 captures[4].downcase != 'w' ? lon = captures[5].to_f + captures[6].to_f/60 : lon = -(captures[5].to_f + captures[6].to_f/60)
365 return "#{lat}, #{lon}"
368 def dms_to_decdeg(captures)
371 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)
372 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)
374 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)
375 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)
377 return "#{lat}, #{lon}"