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 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)
21 @sources.push "uk_postcode"
22 @sources.push "osm_nominatim"
23 @sources.push "osm_namefinder"
24 elsif @query.match(/^[A-Z]\d[A-Z]\s*\d[A-Z]\d$/i)
25 @sources.push "ca_postcode"
27 @sources.push "osm_nominatim"
28 @sources.push "osm_namefinder"
29 @sources.push "geonames"
32 render :update do |page|
33 page.replace_html :sidebar_content, :partial => "search"
34 page.call "openSidebar"
39 # get query parameters
40 query = params[:query]
46 if m = query.match(/^\s*([+-]?\d+(\.\d*)?)\s*[\s,]\s*([+-]?\d+(\.\d*)?)\s*$/)
52 if lat < -90 or lat > 90
53 @error = "Latitude #{lat} out of range"
54 render :action => "error"
55 elsif lon < -180 or lon > 180
56 @error = "Longitude #{lon} out of range"
57 render :action => "error"
59 @results.push({:lat => lat, :lon => lon,
60 :zoom => APP_CONFIG['postcode_zoom'],
61 :name => "#{lat}, #{lon}"})
63 render :action => "results"
67 def search_us_postcode
68 # get query parameters
69 query = params[:query]
74 # ask geocoder.us (they have a non-commercial use api)
75 response = fetch_text("http://rpc.geocoder.us/service/csv?zip=#{escape_query(query)}")
78 unless response.match(/couldn't find this zip/)
79 data = response.split(/\s*,\s+/) # lat,long,town,state,zip
80 @results.push({:lat => data[0], :lon => data[1],
81 :zoom => APP_CONFIG['postcode_zoom'],
82 :prefix => "#{data[2]}, #{data[3]},",
86 render :action => "results"
87 rescue Exception => ex
88 @error = "Error contacting rpc.geocoder.us: #{ex.to_s}"
89 render :action => "error"
92 def search_uk_postcode
93 # get query parameters
94 query = params[:query]
99 # ask npemap.org.uk to do a combined npemap + freethepostcode search
100 response = fetch_text("http://www.npemap.org.uk/cgi/geocoder.fcgi?format=text&postcode=#{escape_query(query)}")
103 unless response.match(/Error/)
104 dataline = response.split(/\n/)[1]
105 data = dataline.split(/,/) # easting,northing,postcode,lat,long
106 postcode = data[2].gsub(/'/, "")
107 zoom = APP_CONFIG['postcode_zoom'] - postcode.count("#")
108 @results.push({:lat => data[3], :lon => data[4], :zoom => zoom,
112 render :action => "results"
113 rescue Exception => ex
114 @error = "Error contacting www.npemap.org.uk: #{ex.to_s}"
115 render :action => "error"
118 def search_ca_postcode
119 # get query parameters
120 query = params[:query]
123 # ask geocoder.ca (note - they have a per-day limit)
124 response = fetch_xml("http://geocoder.ca/?geoit=XML&postal=#{escape_query(query)}")
127 if response.get_elements("geodata/error").empty?
128 @results.push({:lat => response.get_text("geodata/latt").to_s,
129 :lon => response.get_text("geodata/longt").to_s,
130 :zoom => APP_CONFIG['postcode_zoom'],
131 :name => query.upcase})
134 render :action => "results"
135 rescue Exception => ex
136 @error = "Error contacting geocoder.ca: #{ex.to_s}"
137 render :action => "error"
140 def search_osm_namefinder
141 # get query parameters
142 query = params[:query]
144 # create result array
148 response = fetch_xml("http://gazetteer.openstreetmap.org/namefinder/search.xml?find=#{escape_query(query)}")
151 response.elements.each("searchresults/named") do |named|
152 lat = named.attributes["lat"].to_s
153 lon = named.attributes["lon"].to_s
154 zoom = named.attributes["zoom"].to_s
155 place = named.elements["place/named"] || named.elements["nearestplaces/named"]
156 type = named.attributes["info"].to_s.capitalize
157 name = named.attributes["name"].to_s
158 description = named.elements["description"].to_s
164 prefix = t "geocoder.search_osm_namefinder.prefix", :type => type
168 distance = format_distance(place.attributes["approxdistance"].to_i)
169 direction = format_direction(place.attributes["direction"].to_i)
170 placename = format_name(place.attributes["name"].to_s)
171 suffix = t "geocoder.search_osm_namefinder.suffix_place", :distance => distance, :direction => direction, :placename => placename
173 if place.attributes["rank"].to_i <= 30
178 place.elements.each("nearestplaces/named") do |nearest|
179 nearestrank = nearest.attributes["rank"].to_i
180 nearestscore = nearestrank / nearest.attributes["distance"].to_f
182 if nearestrank > 30 and
183 ( nearestscore > parentscore or
184 ( nearestscore == parentscore and nearestrank > parentrank ) )
186 parentrank = nearestrank
187 parentscore = nearestscore
192 parentname = format_name(parent.attributes["name"].to_s)
194 if place.attributes["info"].to_s == "suburb"
195 suffix = t "geocoder.search_osm_namefinder.suffix_suburb", :suffix => suffix, :parentname => parentname
197 parentdistance = format_distance(parent.attributes["approxdistance"].to_i)
198 parentdirection = format_direction(parent.attributes["direction"].to_i)
199 suffix = t "geocoder.search_osm_namefinder.suffix_parent", :suffix => suffix, :parentdistance => parentdistance, :parentdirection => parentdirection, :parentname => parentname
207 @results.push({:lat => lat, :lon => lon, :zoom => zoom,
208 :prefix => prefix, :name => name, :suffix => suffix,
209 :description => description})
212 render :action => "results"
213 rescue Exception => ex
214 @error = "Error contacting gazetteer.openstreetmap.org: #{ex.to_s}"
215 render :action => "error"
218 def search_osm_nominatim
219 # get query parameters
220 query = params[:query]
221 minlon = params[:minlon]
222 minlat = params[:minlat]
223 maxlon = params[:maxlon]
224 maxlat = params[:maxlat]
227 if minlon && minlat && maxlon && maxlat
228 viewbox = "&viewbox=#{minlon},#{maxlat},#{maxlon},#{minlat}"
231 # get objects to excude
233 exclude = "&exclude_place_ids=#{params[:exclude].join(',')}"
237 response = fetch_xml("http://nominatim.openstreetmap.org/search?format=xml&q=#{escape_query(query)}#{viewbox}#{exclude}&accept-language=#{request.user_preferred_languages.join(',')}")
239 # create result array
242 # create parameter hash for "more results" link
243 @more_params = params.reverse_merge({ :exclude => [] })
245 # extract the results from the response
246 results = response.elements["searchresults"]
249 results.elements.each("place") do |place|
250 lat = place.attributes["lat"].to_s
251 lon = place.attributes["lon"].to_s
252 klass = place.attributes["class"].to_s
253 type = place.attributes["type"].to_s
254 name = place.attributes["display_name"].to_s
255 min_lat,max_lat,min_lon,max_lon = place.attributes["boundingbox"].to_s.split(",")
256 prefix = t "geocoder.search_osm_nominatim.prefix.#{klass}.#{type}", :default => type.gsub("_", " ").capitalize
258 @results.push({:lat => lat, :lon => lon,
259 :min_lat => min_lat, :max_lat => max_lat,
260 :min_lon => min_lon, :max_lon => max_lon,
261 :prefix => prefix, :name => name})
262 @more_params[:exclude].push(place.attributes["place_id"].to_s)
265 render :action => "results"
266 rescue Exception => ex
267 @error = "Error contacting nominatim.openstreetmap.org: #{ex.to_s}"
268 render :action => "error"
272 # get query parameters
273 query = params[:query]
275 # create result array
279 response = fetch_xml("http://ws.geonames.org/search?q=#{escape_query(query)}&maxRows=20")
282 response.elements.each("geonames/geoname") do |geoname|
283 lat = geoname.get_text("lat").to_s
284 lon = geoname.get_text("lng").to_s
285 name = geoname.get_text("name").to_s
286 country = geoname.get_text("countryName").to_s
287 @results.push({:lat => lat, :lon => lon,
288 :zoom => APP_CONFIG['geonames_zoom'],
290 :suffix => ", #{country}"})
293 render :action => "results"
294 rescue Exception => ex
295 @error = "Error contacting ws.geonames.org: #{ex.to_s}"
296 render :action => "error"
302 @sources.push({ :name => "osm_nominatim" })
303 @sources.push({ :name => "osm_namefinder", :types => "cities", :max => 2 })
304 @sources.push({ :name => "osm_namefinder", :types => "towns", :max => 4 })
305 @sources.push({ :name => "osm_namefinder", :types => "places", :max => 10 })
306 @sources.push({ :name => "geonames" })
308 render :update do |page|
309 page.replace_html :sidebar_content, :partial => "description"
310 page.call "openSidebar"
314 def description_osm_namefinder
315 # get query parameters
318 types = params[:types]
321 # create result array
325 response = fetch_xml("http://gazetteer.openstreetmap.org/namefinder/search.xml?find=#{types}+near+#{lat},#{lon}&max=#{max}")
328 response.elements.each("searchresults/named") do |named|
329 lat = named.attributes["lat"].to_s
330 lon = named.attributes["lon"].to_s
331 zoom = named.attributes["zoom"].to_s
332 place = named.elements["place/named"] || named.elements["nearestplaces/named"]
333 type = named.attributes["info"].to_s
334 name = named.attributes["name"].to_s
335 description = named.elements["description"].to_s
336 distance = format_distance(place.attributes["approxdistance"].to_i)
337 direction = format_direction((place.attributes["direction"].to_i - 180) % 360)
338 prefix = t "geocoder.description_osm_namefinder.prefix", :distance => distance, :direction => direction, :type => type
339 @results.push({:lat => lat, :lon => lon, :zoom => zoom,
340 :prefix => prefix.capitalize, :name => name,
341 :description => description})
344 render :action => "results"
345 rescue Exception => ex
346 @error = "Error contacting gazetteer.openstreetmap.org: #{ex.to_s}"
347 render :action => "error"
350 def description_osm_nominatim
351 # get query parameters
356 # create result array
360 response = fetch_xml("http://nominatim.openstreetmap.org/reverse?lat=#{lat}&lon=#{lon}&zoom=#{zoom}&accept-language=#{request.user_preferred_languages.join(',')}")
363 response.elements.each("reversegeocode") do |result|
364 description = result.get_text("result").to_s
366 @results.push({:prefix => "#{description}"})
369 render :action => "results"
370 rescue Exception => ex
371 @error = "Error contacting nominatim.openstreetmap.org: #{ex.to_s}"
372 render :action => "error"
375 def description_geonames
376 # get query parameters
380 # create result array
384 response = fetch_xml("http://ws.geonames.org/countrySubdivision?lat=#{lat}&lng=#{lon}")
387 response.elements.each("geonames/countrySubdivision") do |geoname|
388 name = geoname.get_text("adminName1").to_s
389 country = geoname.get_text("countryName").to_s
390 @results.push({:prefix => "#{name}, #{country}"})
393 render :action => "results"
394 rescue Exception => ex
395 @error = "Error contacting ws.geonames.org: #{ex.to_s}"
396 render :action => "error"
402 return Net::HTTP.get(URI.parse(url))
406 return REXML::Document.new(fetch_text(url))
409 def format_distance(distance)
410 return t("geocoder.distance", :count => distance)
413 def format_direction(bearing)
414 return t("geocoder.direction.south_west") if bearing >= 22.5 and bearing < 67.5
415 return t("geocoder.direction.south") if bearing >= 67.5 and bearing < 112.5
416 return t("geocoder.direction.south_east") if bearing >= 112.5 and bearing < 157.5
417 return t("geocoder.direction.east") if bearing >= 157.5 and bearing < 202.5
418 return t("geocoder.direction.north_east") if bearing >= 202.5 and bearing < 247.5
419 return t("geocoder.direction.north") if bearing >= 247.5 and bearing < 292.5
420 return t("geocoder.direction.north_west") if bearing >= 292.5 and bearing < 337.5
421 return t("geocoder.direction.west")
424 def format_name(name)
425 return name.gsub(/( *\[[^\]]*\])*$/, "")
428 def count_results(results)
431 results.each do |source|
432 count += source[:results].length if source[:results]
438 def escape_query(query)
439 return URI.escape(query, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]", false, 'N'))