3 class GeocoderController < ApplicationController
6 require 'rexml/document'
8 before_filter :authorize_web
9 before_filter :set_locale
15 if params[:lat] && params[:lon]
16 @sources.push "osm_nominatim_reverse"
17 @sources.push "geonames_reverse"
18 elsif params[:query].match(/^\d{5}(-\d{4})?$/)
19 @sources.push "us_postcode"
20 @sources.push "osm_nominatim"
21 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)
22 @sources.push "uk_postcode"
23 @sources.push "osm_nominatim"
24 elsif params[:query].match(/^[A-Z]\d[A-Z]\s*\d[A-Z]\d$/i)
25 @sources.push "ca_postcode"
26 @sources.push "osm_nominatim"
28 @sources.push "osm_nominatim"
29 @sources.push "geonames" if defined?(GEONAMES_USERNAME)
32 render :layout => map_layout
35 def search_us_postcode
36 # get query parameters
37 query = params[:query]
42 # ask geocoder.us (they have a non-commercial use api)
43 response = fetch_text("http://rpc.geocoder.us/service/csv?zip=#{escape_query(query)}")
46 unless response.match(/couldn't find this zip/)
47 data = response.split(/\s*,\s+/) # lat,long,town,state,zip
48 @results.push({:lat => data[0], :lon => data[1],
49 :zoom => POSTCODE_ZOOM,
50 :prefix => "#{data[2]}, #{data[3]},",
54 render :action => "results"
55 rescue Exception => ex
56 @error = "Error contacting rpc.geocoder.us: #{ex.to_s}"
57 render :action => "error"
60 def search_uk_postcode
61 # get query parameters
62 query = params[:query]
67 # ask npemap.org.uk to do a combined npemap + freethepostcode search
68 response = fetch_text("http://www.npemap.org.uk/cgi/geocoder.fcgi?format=text&postcode=#{escape_query(query)}")
71 unless response.match(/Error/)
72 dataline = response.split(/\n/)[1]
73 data = dataline.split(/,/) # easting,northing,postcode,lat,long
74 postcode = data[2].gsub(/'/, "")
75 zoom = POSTCODE_ZOOM - postcode.count("#")
76 @results.push({:lat => data[3], :lon => data[4], :zoom => zoom,
80 render :action => "results"
81 rescue Exception => ex
82 @error = "Error contacting www.npemap.org.uk: #{ex.to_s}"
83 render :action => "error"
86 def search_ca_postcode
87 # get query parameters
88 query = params[:query]
91 # ask geocoder.ca (note - they have a per-day limit)
92 response = fetch_xml("http://geocoder.ca/?geoit=XML&postal=#{escape_query(query)}")
95 if response.get_elements("geodata/error").empty?
96 @results.push({:lat => response.get_text("geodata/latt").to_s,
97 :lon => response.get_text("geodata/longt").to_s,
98 :zoom => POSTCODE_ZOOM,
99 :name => query.upcase})
102 render :action => "results"
103 rescue Exception => ex
104 @error = "Error contacting geocoder.ca: #{ex.to_s}"
105 render :action => "error"
108 def search_osm_nominatim
109 # get query parameters
110 query = params[:query]
111 minlon = params[:minlon]
112 minlat = params[:minlat]
113 maxlon = params[:maxlon]
114 maxlat = params[:maxlat]
117 if minlon && minlat && maxlon && maxlat
118 viewbox = "&viewbox=#{minlon},#{maxlat},#{maxlon},#{minlat}"
121 # get objects to excude
123 exclude = "&exclude_place_ids=#{params[:exclude].join(',')}"
127 response = fetch_xml("#{NOMINATIM_URL}search?format=xml&q=#{escape_query(query)}#{viewbox}#{exclude}&accept-language=#{http_accept_language.user_preferred_languages.join(',')}")
129 # create result array
132 # create parameter hash for "more results" link
133 @more_params = params.reverse_merge({ :exclude => [] })
135 # extract the results from the response
136 results = response.elements["searchresults"]
139 results.elements.each("place") do |place|
140 lat = place.attributes["lat"].to_s
141 lon = place.attributes["lon"].to_s
142 klass = place.attributes["class"].to_s
143 type = place.attributes["type"].to_s
144 name = place.attributes["display_name"].to_s
145 min_lat,max_lat,min_lon,max_lon = place.attributes["boundingbox"].to_s.split(",")
146 prefix_name = t "geocoder.search_osm_nominatim.prefix.#{klass}.#{type}", :default => type.gsub("_", " ").capitalize
147 if klass == 'boundary' and type == 'administrative'
148 rank = (place.attributes["place_rank"].to_i + 1) / 2
149 prefix_name = t "geocoder.search_osm_nominatim.admin_levels.level#{rank}", :default => prefix_name
151 prefix = t "geocoder.search_osm_nominatim.prefix_format", :name => prefix_name
152 object_type = place.attributes["osm_type"]
153 object_id = place.attributes["osm_id"]
155 @results.push({:lat => lat, :lon => lon,
156 :min_lat => min_lat, :max_lat => max_lat,
157 :min_lon => min_lon, :max_lon => max_lon,
158 :prefix => prefix, :name => name,
159 :type => object_type, :id => object_id})
160 @more_params[:exclude].push(place.attributes["place_id"].to_s)
163 render :action => "results"
164 # rescue Exception => ex
165 # @error = "Error contacting nominatim.openstreetmap.org: #{ex.to_s}"
166 # render :action => "error"
170 # get query parameters
171 query = params[:query]
173 # create result array
177 response = fetch_xml("http://api.geonames.org/search?q=#{escape_query(query)}&maxRows=20&username=#{GEONAMES_USERNAME}")
180 response.elements.each("geonames/geoname") do |geoname|
181 lat = geoname.get_text("lat").to_s
182 lon = geoname.get_text("lng").to_s
183 name = geoname.get_text("name").to_s
184 country = geoname.get_text("countryName").to_s
185 @results.push({:lat => lat, :lon => lon,
186 :zoom => GEONAMES_ZOOM,
188 :suffix => ", #{country}"})
191 render :action => "results"
192 rescue Exception => ex
193 @error = "Error contacting ws.geonames.org: #{ex.to_s}"
194 render :action => "error"
197 def search_osm_nominatim_reverse
198 # get query parameters
203 # create result array
207 response = fetch_xml("#{NOMINATIM_URL}reverse?lat=#{lat}&lon=#{lon}&zoom=#{zoom}&accept-language=#{http_accept_language.user_preferred_languages.join(',')}")
210 response.elements.each("reversegeocode/result") do |result|
211 lat = result.attributes["lat"].to_s
212 lon = result.attributes["lon"].to_s
213 object_type = result.attributes["osm_type"]
214 object_id = result.attributes["osm_id"]
215 description = result.get_text.to_s
217 @results.push({:lat => lat, :lon => lon,
219 :name => description,
220 :type => object_type, :id => object_id})
223 render :action => "results"
224 rescue Exception => ex
225 @error = "Error contacting nominatim.openstreetmap.org: #{ex.to_s}"
226 render :action => "error"
229 def search_geonames_reverse
230 # get query parameters
234 # create result array
238 response = fetch_xml("http://ws.geonames.org/countrySubdivision?lat=#{lat}&lng=#{lon}")
241 response.elements.each("geonames/countrySubdivision") do |geoname|
242 name = geoname.get_text("adminName1").to_s
243 country = geoname.get_text("countryName").to_s
244 @results.push({:lat => lat, :lon => lon,
245 :zoom => GEONAMES_ZOOM,
247 :suffix => ", #{country}"})
250 render :action => "results"
251 rescue Exception => ex
252 @error = "Error contacting ws.geonames.org: #{ex.to_s}"
253 render :action => "error"
259 return Net::HTTP.get(URI.parse(url))
263 return REXML::Document.new(fetch_text(url))
266 def format_distance(distance)
267 return t("geocoder.distance", :count => distance)
270 def format_direction(bearing)
271 return t("geocoder.direction.south_west") if bearing >= 22.5 and bearing < 67.5
272 return t("geocoder.direction.south") if bearing >= 67.5 and bearing < 112.5
273 return t("geocoder.direction.south_east") if bearing >= 112.5 and bearing < 157.5
274 return t("geocoder.direction.east") if bearing >= 157.5 and bearing < 202.5
275 return t("geocoder.direction.north_east") if bearing >= 202.5 and bearing < 247.5
276 return t("geocoder.direction.north") if bearing >= 247.5 and bearing < 292.5
277 return t("geocoder.direction.north_west") if bearing >= 292.5 and bearing < 337.5
278 return t("geocoder.direction.west")
281 def format_name(name)
282 return name.gsub(/( *\[[^\]]*\])*$/, "")
285 def count_results(results)
288 results.each do |source|
289 count += source[:results].length if source[:results]
295 def escape_query(query)
296 return URI.escape(query, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]", false, 'N'))
300 query = params[:query]
305 if latlon = query.match(/^([NS])\s*(\d{1,3}(\.\d*)?)\W*([EW])\s*(\d{1,3}(\.\d*)?)$/).try(:captures) # [NSEW] decimal degrees
306 params.merge!(nsew_to_decdeg(latlon)).delete(:query)
307 elsif latlon = query.match(/^(\d{1,3}(\.\d*)?)\s*([NS])\W*(\d{1,3}(\.\d*)?)\s*([EW])$/).try(:captures) # decimal degrees [NSEW]
308 params.merge!(nsew_to_decdeg(latlon)).delete(:query)
310 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
311 params.merge!(ddm_to_decdeg(latlon)).delete(:query)
312 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]
313 params.merge!(ddm_to_decdeg(latlon)).delete(:query)
315 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
316 params.merge!(dms_to_decdeg(latlon)).delete(:query)
317 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]
318 params.merge!(dms_to_decdeg(latlon)).delete(:query)
320 elsif latlon = query.match(/^\s*([+-]?\d+(\.\d*)?)\s*[\s,]\s*([+-]?\d+(\.\d*)?)\s*$/)
321 params.merge!({:lat => latlon[1].to_f, :lon => latlon[3].to_f}).delete(:query)
325 def nsew_to_decdeg(captures)
328 captures[2].downcase != 's' ? lat = captures[0].to_f : lat = -(captures[0].to_f)
329 captures[5].downcase != 'w' ? lon = captures[3].to_f : lon = -(captures[3].to_f)
331 captures[0].downcase != 's' ? lat = captures[1].to_f : lat = -(captures[1].to_f)
332 captures[3].downcase != 'w' ? lon = captures[4].to_f : lon = -(captures[4].to_f)
334 {:lat => lat, :lon => lon}
337 def ddm_to_decdeg(captures)
340 captures[3].downcase != 's' ? lat = captures[0].to_f + captures[1].to_f/60 : lat = -(captures[0].to_f + captures[1].to_f/60)
341 captures[7].downcase != 'w' ? lon = captures[4].to_f + captures[5].to_f/60 : lon = -(captures[4].to_f + captures[5].to_f/60)
343 captures[0].downcase != 's' ? lat = captures[1].to_f + captures[2].to_f/60 : lat = -(captures[1].to_f + captures[2].to_f/60)
344 captures[4].downcase != 'w' ? lon = captures[5].to_f + captures[6].to_f/60 : lon = -(captures[5].to_f + captures[6].to_f/60)
346 {:lat => lat, :lon => lon}
349 def dms_to_decdeg(captures)
352 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)
353 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)
355 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)
356 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)
358 {:lat => lat, :lon => lon}