1 class GeocoderController < ApplicationController
4 require 'rexml/document'
6 before_filter :authorize_web
7 before_filter :set_locale
10 @query = params[:query]
13 @query.sub(/^\s+/, "")
14 @query.sub(/\s+$/, "")
16 if @query.match(/^[+-]?\d+(\.\d*)?\s*[\s,]\s*[+-]?\d+(\.\d*)?$/)
17 @sources.push "latlon"
18 elsif @query.match(/^\d{5}(-\d{4})?$/)
19 @sources.push "us_postcode"
20 @sources.push "osm_nominatim"
21 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)
22 @sources.push "uk_postcode"
23 @sources.push "osm_nominatim"
24 elsif @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)
34 # get query parameters
35 query = params[:query]
41 if m = query.match(/^\s*([+-]?\d+(\.\d*)?)\s*[\s,]\s*([+-]?\d+(\.\d*)?)\s*$/)
47 if lat < -90 or lat > 90
48 @error = "Latitude #{lat} out of range"
49 render :action => "error"
50 elsif lon < -180 or lon > 180
51 @error = "Longitude #{lon} out of range"
52 render :action => "error"
54 @results.push({:lat => lat, :lon => lon,
55 :zoom => POSTCODE_ZOOM,
56 :name => "#{lat}, #{lon}"})
58 render :action => "results"
62 def search_us_postcode
63 # get query parameters
64 query = params[:query]
69 # ask geocoder.us (they have a non-commercial use api)
70 response = fetch_text("http://rpc.geocoder.us/service/csv?zip=#{escape_query(query)}")
73 unless response.match(/couldn't find this zip/)
74 data = response.split(/\s*,\s+/) # lat,long,town,state,zip
75 @results.push({:lat => data[0], :lon => data[1],
76 :zoom => POSTCODE_ZOOM,
77 :prefix => "#{data[2]}, #{data[3]},",
81 render :action => "results"
82 rescue Exception => ex
83 @error = "Error contacting rpc.geocoder.us: #{ex.to_s}"
84 render :action => "error"
87 def search_uk_postcode
88 # get query parameters
89 query = params[:query]
94 # ask npemap.org.uk to do a combined npemap + freethepostcode search
95 response = fetch_text("http://www.npemap.org.uk/cgi/geocoder.fcgi?format=text&postcode=#{escape_query(query)}")
98 unless response.match(/Error/)
99 dataline = response.split(/\n/)[1]
100 data = dataline.split(/,/) # easting,northing,postcode,lat,long
101 postcode = data[2].gsub(/'/, "")
102 zoom = POSTCODE_ZOOM - postcode.count("#")
103 @results.push({:lat => data[3], :lon => data[4], :zoom => zoom,
107 render :action => "results"
108 rescue Exception => ex
109 @error = "Error contacting www.npemap.org.uk: #{ex.to_s}"
110 render :action => "error"
113 def search_ca_postcode
114 # get query parameters
115 query = params[:query]
118 # ask geocoder.ca (note - they have a per-day limit)
119 response = fetch_xml("http://geocoder.ca/?geoit=XML&postal=#{escape_query(query)}")
122 if response.get_elements("geodata/error").empty?
123 @results.push({:lat => response.get_text("geodata/latt").to_s,
124 :lon => response.get_text("geodata/longt").to_s,
125 :zoom => POSTCODE_ZOOM,
126 :name => query.upcase})
129 render :action => "results"
130 rescue Exception => ex
131 @error = "Error contacting geocoder.ca: #{ex.to_s}"
132 render :action => "error"
135 def search_osm_nominatim
136 # get query parameters
137 query = params[:query]
138 minlon = params[:minlon]
139 minlat = params[:minlat]
140 maxlon = params[:maxlon]
141 maxlat = params[:maxlat]
144 if minlon && minlat && maxlon && maxlat
145 viewbox = "&viewbox=#{minlon},#{maxlat},#{maxlon},#{minlat}"
148 # get objects to excude
150 exclude = "&exclude_place_ids=#{params[:exclude].join(',')}"
154 response = fetch_xml("#{NOMINATIM_URL}search?format=xml&q=#{escape_query(query)}#{viewbox}#{exclude}&accept-language=#{request.user_preferred_languages.join(',')}")
156 # create result array
159 # create parameter hash for "more results" link
160 @more_params = params.reverse_merge({ :exclude => [] })
162 # extract the results from the response
163 results = response.elements["searchresults"]
166 results.elements.each("place") do |place|
167 lat = place.attributes["lat"].to_s
168 lon = place.attributes["lon"].to_s
169 klass = place.attributes["class"].to_s
170 type = place.attributes["type"].to_s
171 name = place.attributes["display_name"].to_s
172 min_lat,max_lat,min_lon,max_lon = place.attributes["boundingbox"].to_s.split(",")
173 prefix_name = t "geocoder.search_osm_nominatim.prefix.#{klass}.#{type}", :default => type.gsub("_", " ").capitalize
174 prefix = t "geocoder.search_osm_nominatim.prefix_format", :name => prefix_name
176 @results.push({:lat => lat, :lon => lon,
177 :min_lat => min_lat, :max_lat => max_lat,
178 :min_lon => min_lon, :max_lon => max_lon,
179 :prefix => prefix, :name => name})
180 @more_params[:exclude].push(place.attributes["place_id"].to_s)
183 render :action => "results"
184 # rescue Exception => ex
185 # @error = "Error contacting nominatim.openstreetmap.org: #{ex.to_s}"
186 # render :action => "error"
190 # get query parameters
191 query = params[:query]
193 # create result array
197 response = fetch_xml("http://api.geonames.org/search?q=#{escape_query(query)}&maxRows=20&username=#{GEONAMES_USERNAME}")
200 response.elements.each("geonames/geoname") do |geoname|
201 lat = geoname.get_text("lat").to_s
202 lon = geoname.get_text("lng").to_s
203 name = geoname.get_text("name").to_s
204 country = geoname.get_text("countryName").to_s
205 @results.push({:lat => lat, :lon => lon,
206 :zoom => GEONAMES_ZOOM,
208 :suffix => ", #{country}"})
211 render :action => "results"
212 rescue Exception => ex
213 @error = "Error contacting ws.geonames.org: #{ex.to_s}"
214 render :action => "error"
220 @sources.push({ :name => "osm_nominatim" })
221 @sources.push({ :name => "geonames" })
224 def description_osm_nominatim
225 # get query parameters
230 # create result array
234 response = fetch_xml("#{NOMINATIM_URL}reverse?lat=#{lat}&lon=#{lon}&zoom=#{zoom}&accept-language=#{request.user_preferred_languages.join(',')}")
237 response.elements.each("reversegeocode/result") do |result|
238 description = result.get_text.to_s
240 @results.push({:prefix => "#{description}"})
243 render :action => "results"
244 rescue Exception => ex
245 @error = "Error contacting nominatim.openstreetmap.org: #{ex.to_s}"
246 render :action => "error"
249 def description_geonames
250 # get query parameters
254 # create result array
258 response = fetch_xml("http://ws.geonames.org/countrySubdivision?lat=#{lat}&lng=#{lon}")
261 response.elements.each("geonames/countrySubdivision") do |geoname|
262 name = geoname.get_text("adminName1").to_s
263 country = geoname.get_text("countryName").to_s
264 @results.push({:prefix => "#{name}, #{country}"})
267 render :action => "results"
268 rescue Exception => ex
269 @error = "Error contacting ws.geonames.org: #{ex.to_s}"
270 render :action => "error"
276 return Net::HTTP.get(URI.parse(url))
280 return REXML::Document.new(fetch_text(url))
283 def format_distance(distance)
284 return t("geocoder.distance", :count => distance)
287 def format_direction(bearing)
288 return t("geocoder.direction.south_west") if bearing >= 22.5 and bearing < 67.5
289 return t("geocoder.direction.south") if bearing >= 67.5 and bearing < 112.5
290 return t("geocoder.direction.south_east") if bearing >= 112.5 and bearing < 157.5
291 return t("geocoder.direction.east") if bearing >= 157.5 and bearing < 202.5
292 return t("geocoder.direction.north_east") if bearing >= 202.5 and bearing < 247.5
293 return t("geocoder.direction.north") if bearing >= 247.5 and bearing < 292.5
294 return t("geocoder.direction.north_west") if bearing >= 292.5 and bearing < 337.5
295 return t("geocoder.direction.west")
298 def format_name(name)
299 return name.gsub(/( *\[[^\]]*\])*$/, "")
302 def count_results(results)
305 results.each do |source|
306 count += source[:results].length if source[:results]
312 def escape_query(query)
313 return URI.escape(query, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]", false, 'N'))