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 if klass == 'boundary' and type == 'administrative'
178 rank = (place.attributes["place_rank"].to_i + 1) / 2
179 prefix_name = t "geocoder.search_osm_nominatim.admin_levels.level#{rank}", :default => prefix_name
181 prefix = t "geocoder.search_osm_nominatim.prefix_format", :name => prefix_name
182 object_type = place.attributes["osm_type"]
183 object_id = place.attributes["osm_id"]
185 @results.push({:lat => lat, :lon => lon,
186 :min_lat => min_lat, :max_lat => max_lat,
187 :min_lon => min_lon, :max_lon => max_lon,
188 :prefix => prefix, :name => name,
189 :type => object_type, :id => object_id})
190 @more_params[:exclude].push(place.attributes["place_id"].to_s)
193 render :action => "results"
194 # rescue Exception => ex
195 # @error = "Error contacting nominatim.openstreetmap.org: #{ex.to_s}"
196 # render :action => "error"
200 # get query parameters
201 query = params[:query]
203 # create result array
207 response = fetch_xml("http://api.geonames.org/search?q=#{escape_query(query)}&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 Exception => ex
223 @error = "Error contacting ws.geonames.org: #{ex.to_s}"
224 render :action => "error"
230 @sources.push({ :name => "osm_nominatim" })
231 @sources.push({ :name => "geonames" })
234 def description_osm_nominatim
235 # get query parameters
240 # create result array
244 response = fetch_xml("#{NOMINATIM_URL}reverse?lat=#{lat}&lon=#{lon}&zoom=#{zoom}&accept-language=#{request.user_preferred_languages.join(',')}")
247 response.elements.each("reversegeocode/result") do |result|
248 description = result.get_text.to_s
250 @results.push({:prefix => "#{description}"})
253 render :action => "results"
254 rescue Exception => ex
255 @error = "Error contacting nominatim.openstreetmap.org: #{ex.to_s}"
256 render :action => "error"
259 def description_geonames
260 # get query parameters
264 # create result array
268 response = fetch_xml("http://ws.geonames.org/countrySubdivision?lat=#{lat}&lng=#{lon}")
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({:prefix => "#{name}, #{country}"})
277 render :action => "results"
278 rescue Exception => ex
279 @error = "Error contacting ws.geonames.org: #{ex.to_s}"
280 render :action => "error"
286 return Net::HTTP.get(URI.parse(url))
290 return REXML::Document.new(fetch_text(url))
293 def format_distance(distance)
294 return t("geocoder.distance", :count => distance)
297 def format_direction(bearing)
298 return t("geocoder.direction.south_west") if bearing >= 22.5 and bearing < 67.5
299 return t("geocoder.direction.south") if bearing >= 67.5 and bearing < 112.5
300 return t("geocoder.direction.south_east") if bearing >= 112.5 and bearing < 157.5
301 return t("geocoder.direction.east") if bearing >= 157.5 and bearing < 202.5
302 return t("geocoder.direction.north_east") if bearing >= 202.5 and bearing < 247.5
303 return t("geocoder.direction.north") if bearing >= 247.5 and bearing < 292.5
304 return t("geocoder.direction.north_west") if bearing >= 292.5 and bearing < 337.5
305 return t("geocoder.direction.west")
308 def format_name(name)
309 return name.gsub(/( *\[[^\]]*\])*$/, "")
312 def count_results(results)
315 results.each do |source|
316 count += source[:results].length if source[:results]
322 def escape_query(query)
323 return URI.escape(query, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]", false, 'N'))
327 @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[:query] = nsew_to_decdeg(latlon)
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[:query] = nsew_to_decdeg(latlon)
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[:query] = ddm_to_decdeg(latlon)
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[:query] = ddm_to_decdeg(latlon)
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[:query] = dms_to_decdeg(latlon)
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[:query] = dms_to_decdeg(latlon)
348 def nsew_to_decdeg(captures)
351 captures[2].downcase != 's' ? lat = captures[0].to_f : lat = -(captures[0].to_f)
352 captures[5].downcase != 'w' ? lon = captures[3].to_f : lon = -(captures[3].to_f)
354 captures[0].downcase != 's' ? lat = captures[1].to_f : lat = -(captures[1].to_f)
355 captures[3].downcase != 'w' ? lon = captures[4].to_f : lon = -(captures[4].to_f)
357 return "#{lat}, #{lon}"
360 def ddm_to_decdeg(captures)
363 captures[3].downcase != 's' ? lat = captures[0].to_f + captures[1].to_f/60 : lat = -(captures[0].to_f + captures[1].to_f/60)
364 captures[7].downcase != 'w' ? lon = captures[4].to_f + captures[5].to_f/60 : lon = -(captures[4].to_f + captures[5].to_f/60)
366 captures[0].downcase != 's' ? lat = captures[1].to_f + captures[2].to_f/60 : lat = -(captures[1].to_f + captures[2].to_f/60)
367 captures[4].downcase != 'w' ? lon = captures[5].to_f + captures[6].to_f/60 : lon = -(captures[5].to_f + captures[6].to_f/60)
369 return "#{lat}, #{lon}"
372 def dms_to_decdeg(captures)
375 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)
376 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)
378 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)
379 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)
381 return "#{lat}, #{lon}"