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)
33 def search_us_postcode
34 # get query parameters
35 query = params[:query]
40 # ask geocoder.us (they have a non-commercial use api)
41 response = fetch_text("http://rpc.geocoder.us/service/csv?zip=#{escape_query(query)}")
44 unless response.match(/couldn't find this zip/)
45 data = response.split(/\s*,\s+/) # lat,long,town,state,zip
46 @results.push({:lat => data[0], :lon => data[1],
47 :zoom => POSTCODE_ZOOM,
48 :prefix => "#{data[2]}, #{data[3]},",
52 render :action => "results"
53 rescue Exception => ex
54 @error = "Error contacting rpc.geocoder.us: #{ex.to_s}"
55 render :action => "error"
58 def search_uk_postcode
59 # get query parameters
60 query = params[:query]
65 # ask npemap.org.uk to do a combined npemap + freethepostcode search
66 response = fetch_text("http://www.npemap.org.uk/cgi/geocoder.fcgi?format=text&postcode=#{escape_query(query)}")
69 unless response.match(/Error/)
70 dataline = response.split(/\n/)[1]
71 data = dataline.split(/,/) # easting,northing,postcode,lat,long
72 postcode = data[2].gsub(/'/, "")
73 zoom = POSTCODE_ZOOM - postcode.count("#")
74 @results.push({:lat => data[3], :lon => data[4], :zoom => zoom,
78 render :action => "results"
79 rescue Exception => ex
80 @error = "Error contacting www.npemap.org.uk: #{ex.to_s}"
81 render :action => "error"
84 def search_ca_postcode
85 # get query parameters
86 query = params[:query]
89 # ask geocoder.ca (note - they have a per-day limit)
90 response = fetch_xml("http://geocoder.ca/?geoit=XML&postal=#{escape_query(query)}")
93 if response.get_elements("geodata/error").empty?
94 @results.push({:lat => response.get_text("geodata/latt").to_s,
95 :lon => response.get_text("geodata/longt").to_s,
96 :zoom => POSTCODE_ZOOM,
97 :name => query.upcase})
100 render :action => "results"
101 rescue Exception => ex
102 @error = "Error contacting geocoder.ca: #{ex.to_s}"
103 render :action => "error"
106 def search_osm_nominatim
107 # get query parameters
108 query = params[:query]
109 minlon = params[:minlon]
110 minlat = params[:minlat]
111 maxlon = params[:maxlon]
112 maxlat = params[:maxlat]
115 if minlon && minlat && maxlon && maxlat
116 viewbox = "&viewbox=#{minlon},#{maxlat},#{maxlon},#{minlat}"
119 # get objects to excude
121 exclude = "&exclude_place_ids=#{params[:exclude].join(',')}"
125 response = fetch_xml("#{NOMINATIM_URL}search?format=xml&q=#{escape_query(query)}#{viewbox}#{exclude}&accept-language=#{http_accept_language.user_preferred_languages.join(',')}")
127 # create result array
130 # create parameter hash for "more results" link
131 @more_params = params.reverse_merge({ :exclude => [] })
133 # extract the results from the response
134 results = response.elements["searchresults"]
137 results.elements.each("place") do |place|
138 lat = place.attributes["lat"].to_s
139 lon = place.attributes["lon"].to_s
140 klass = place.attributes["class"].to_s
141 type = place.attributes["type"].to_s
142 name = place.attributes["display_name"].to_s
143 min_lat,max_lat,min_lon,max_lon = place.attributes["boundingbox"].to_s.split(",")
144 prefix_name = t "geocoder.search_osm_nominatim.prefix.#{klass}.#{type}", :default => type.gsub("_", " ").capitalize
145 if klass == 'boundary' and type == 'administrative'
146 rank = (place.attributes["place_rank"].to_i + 1) / 2
147 prefix_name = t "geocoder.search_osm_nominatim.admin_levels.level#{rank}", :default => prefix_name
149 prefix = t "geocoder.search_osm_nominatim.prefix_format", :name => prefix_name
150 object_type = place.attributes["osm_type"]
151 object_id = place.attributes["osm_id"]
153 @results.push({:lat => lat, :lon => lon,
154 :min_lat => min_lat, :max_lat => max_lat,
155 :min_lon => min_lon, :max_lon => max_lon,
156 :prefix => prefix, :name => name,
157 :type => object_type, :id => object_id})
158 @more_params[:exclude].push(place.attributes["place_id"].to_s)
161 render :action => "results"
162 # rescue Exception => ex
163 # @error = "Error contacting nominatim.openstreetmap.org: #{ex.to_s}"
164 # render :action => "error"
168 # get query parameters
169 query = params[:query]
171 # create result array
175 response = fetch_xml("http://api.geonames.org/search?q=#{escape_query(query)}&maxRows=20&username=#{GEONAMES_USERNAME}")
178 response.elements.each("geonames/geoname") do |geoname|
179 lat = geoname.get_text("lat").to_s
180 lon = geoname.get_text("lng").to_s
181 name = geoname.get_text("name").to_s
182 country = geoname.get_text("countryName").to_s
183 @results.push({:lat => lat, :lon => lon,
184 :zoom => GEONAMES_ZOOM,
186 :suffix => ", #{country}"})
189 render :action => "results"
190 rescue Exception => ex
191 @error = "Error contacting ws.geonames.org: #{ex.to_s}"
192 render :action => "error"
195 def search_osm_nominatim_reverse
196 # get query parameters
201 # create result array
205 response = fetch_xml("#{NOMINATIM_URL}reverse?lat=#{lat}&lon=#{lon}&zoom=#{zoom}&accept-language=#{http_accept_language.user_preferred_languages.join(',')}")
208 response.elements.each("reversegeocode/result") do |result|
209 lat = result.attributes["lat"].to_s
210 lon = result.attributes["lon"].to_s
211 object_type = result.attributes["osm_type"]
212 object_id = result.attributes["osm_id"]
213 description = result.get_text.to_s
215 @results.push({:lat => lat, :lon => lon,
217 :name => description,
218 :type => object_type, :id => object_id})
221 render :action => "results"
222 rescue Exception => ex
223 @error = "Error contacting nominatim.openstreetmap.org: #{ex.to_s}"
224 render :action => "error"
227 def search_geonames_reverse
228 # get query parameters
232 # create result array
236 response = fetch_xml("http://ws.geonames.org/countrySubdivision?lat=#{lat}&lng=#{lon}")
239 response.elements.each("geonames/countrySubdivision") do |geoname|
240 name = geoname.get_text("adminName1").to_s
241 country = geoname.get_text("countryName").to_s
242 @results.push({:lat => lat, :lon => lon,
243 :zoom => GEONAMES_ZOOM,
245 :suffix => ", #{country}"})
248 render :action => "results"
249 rescue Exception => ex
250 @error = "Error contacting ws.geonames.org: #{ex.to_s}"
251 render :action => "error"
257 return Net::HTTP.get(URI.parse(url))
261 return REXML::Document.new(fetch_text(url))
264 def format_distance(distance)
265 return t("geocoder.distance", :count => distance)
268 def format_direction(bearing)
269 return t("geocoder.direction.south_west") if bearing >= 22.5 and bearing < 67.5
270 return t("geocoder.direction.south") if bearing >= 67.5 and bearing < 112.5
271 return t("geocoder.direction.south_east") if bearing >= 112.5 and bearing < 157.5
272 return t("geocoder.direction.east") if bearing >= 157.5 and bearing < 202.5
273 return t("geocoder.direction.north_east") if bearing >= 202.5 and bearing < 247.5
274 return t("geocoder.direction.north") if bearing >= 247.5 and bearing < 292.5
275 return t("geocoder.direction.north_west") if bearing >= 292.5 and bearing < 337.5
276 return t("geocoder.direction.west")
279 def format_name(name)
280 return name.gsub(/( *\[[^\]]*\])*$/, "")
283 def count_results(results)
286 results.each do |source|
287 count += source[:results].length if source[:results]
293 def escape_query(query)
294 return URI.escape(query, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]", false, 'N'))
298 query = params[:query]
303 if latlon = query.match(/^([NS])\s*(\d{1,3}(\.\d*)?)\W*([EW])\s*(\d{1,3}(\.\d*)?)$/).try(:captures) # [NSEW] decimal degrees
304 params.merge!(nsew_to_decdeg(latlon)).delete(:query)
305 elsif latlon = query.match(/^(\d{1,3}(\.\d*)?)\s*([NS])\W*(\d{1,3}(\.\d*)?)\s*([EW])$/).try(:captures) # decimal degrees [NSEW]
306 params.merge!(nsew_to_decdeg(latlon)).delete(:query)
308 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
309 params.merge!(ddm_to_decdeg(latlon)).delete(:query)
310 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]
311 params.merge!(ddm_to_decdeg(latlon)).delete(:query)
313 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
314 params.merge!(dms_to_decdeg(latlon)).delete(:query)
315 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]
316 params.merge!(dms_to_decdeg(latlon)).delete(:query)
318 elsif latlon = query.match(/^\s*([+-]?\d+(\.\d*)?)\s*[\s,]\s*([+-]?\d+(\.\d*)?)\s*$/)
319 params.merge!({:lat => latlon[1].to_f, :lon => latlon[3].to_f}).delete(:query)
323 def nsew_to_decdeg(captures)
326 captures[2].downcase != 's' ? lat = captures[0].to_f : lat = -(captures[0].to_f)
327 captures[5].downcase != 'w' ? lon = captures[3].to_f : lon = -(captures[3].to_f)
329 captures[0].downcase != 's' ? lat = captures[1].to_f : lat = -(captures[1].to_f)
330 captures[3].downcase != 'w' ? lon = captures[4].to_f : lon = -(captures[4].to_f)
332 {:lat => lat, :lon => lon}
335 def ddm_to_decdeg(captures)
338 captures[3].downcase != 's' ? lat = captures[0].to_f + captures[1].to_f/60 : lat = -(captures[0].to_f + captures[1].to_f/60)
339 captures[7].downcase != 'w' ? lon = captures[4].to_f + captures[5].to_f/60 : lon = -(captures[4].to_f + captures[5].to_f/60)
341 captures[0].downcase != 's' ? lat = captures[1].to_f + captures[2].to_f/60 : lat = -(captures[1].to_f + captures[2].to_f/60)
342 captures[4].downcase != 'w' ? lon = captures[5].to_f + captures[6].to_f/60 : lon = -(captures[5].to_f + captures[6].to_f/60)
344 {:lat => lat, :lon => lon}
347 def dms_to_decdeg(captures)
350 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)
351 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)
353 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)
354 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)
356 {:lat => lat, :lon => lon}