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_namefinder"
23 elsif @query.match(/^[A-Z]\d[A-Z]\s*\d[A-Z]\d$/i)
24 @sources.push "ca_postcode"
26 @sources.push "osm_namefinder"
27 @sources.push "geonames"
30 render :update do |page|
31 page.replace_html :sidebar_content, :partial => "search"
32 page.call "openSidebar"
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 => APP_CONFIG['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 => APP_CONFIG['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 = APP_CONFIG['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 => APP_CONFIG['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_namefinder
139 # get query parameters
140 query = params[:query]
142 # create result array
146 response = fetch_xml("http://gazetteer.openstreetmap.org/namefinder/search.xml?find=#{escape_query(query)}")
149 response.elements.each("searchresults/named") do |named|
150 lat = named.attributes["lat"].to_s
151 lon = named.attributes["lon"].to_s
152 zoom = named.attributes["zoom"].to_s
153 place = named.elements["place/named"] || named.elements["nearestplaces/named"]
154 type = named.attributes["info"].to_s.capitalize
155 name = named.attributes["name"].to_s
156 description = named.elements["description"].to_s
162 prefix = t "geocoder.search_osm_namefinder.prefix", :type => type
166 distance = format_distance(place.attributes["approxdistance"].to_i)
167 direction = format_direction(place.attributes["direction"].to_i)
168 placename = format_name(place.attributes["name"].to_s)
169 suffix = t "geocoder.search_osm_namefinder.suffix_place", :distance => distance, :direction => direction, :placename => placename
171 if place.attributes["rank"].to_i <= 30
176 place.elements.each("nearestplaces/named") do |nearest|
177 nearestrank = nearest.attributes["rank"].to_i
178 nearestscore = nearestrank / nearest.attributes["distance"].to_f
180 if nearestrank > 30 and
181 ( nearestscore > parentscore or
182 ( nearestscore == parentscore and nearestrank > parentrank ) )
184 parentrank = nearestrank
185 parentscore = nearestscore
190 parentname = format_name(parent.attributes["name"].to_s)
192 if place.attributes["info"].to_s == "suburb"
193 suffix = t "geocoder.search_osm_namefinder.suffix_suburb", :suffix => suffix, :parentname => parentname
195 parentdistance = format_distance(parent.attributes["approxdistance"].to_i)
196 parentdirection = format_direction(parent.attributes["direction"].to_i)
197 suffix = t "geocoder.search_osm_namefinder.suffix_parent", :suffix => suffix, :parentdistance => parentdistance, :parentdirection => parentdirection, :parentname => parentname
205 @results.push({:lat => lat, :lon => lon, :zoom => zoom,
206 :prefix => prefix, :name => name, :suffix => suffix,
207 :description => description})
210 render :action => "results"
211 rescue Exception => ex
212 @error = "Error contacting gazetteer.openstreetmap.org: #{ex.to_s}"
213 render :action => "error"
217 # get query parameters
218 query = params[:query]
220 # create result array
224 response = fetch_xml("http://ws.geonames.org/search?q=#{escape_query(query)}&maxRows=20")
227 response.elements.each("geonames/geoname") do |geoname|
228 lat = geoname.get_text("lat").to_s
229 lon = geoname.get_text("lng").to_s
230 name = geoname.get_text("name").to_s
231 country = geoname.get_text("countryName").to_s
232 @results.push({:lat => lat, :lon => lon,
233 :zoom => APP_CONFIG['geonames_zoom'],
235 :suffix => ", #{country}"})
238 render :action => "results"
239 rescue Exception => ex
240 @error = "Error contacting ws.geonames.org: #{ex.to_s}"
241 render :action => "error"
247 @sources.push({ :name => "osm_namefinder", :types => "cities", :max => 2 })
248 @sources.push({ :name => "osm_namefinder", :types => "towns", :max => 4 })
249 @sources.push({ :name => "osm_namefinder", :types => "places", :max => 10 })
250 @sources.push({ :name => "geonames" })
252 render :update do |page|
253 page.replace_html :sidebar_content, :partial => "description"
254 page.call "openSidebar"
258 def description_osm_namefinder
259 # get query parameters
262 types = params[:types]
265 # create result array
269 response = fetch_xml("http://gazetteer.openstreetmap.org/namefinder/search.xml?find=#{types}+near+#{lat},#{lon}&max=#{max}")
272 response.elements.each("searchresults/named") do |named|
273 lat = named.attributes["lat"].to_s
274 lon = named.attributes["lon"].to_s
275 zoom = named.attributes["zoom"].to_s
276 place = named.elements["place/named"] || named.elements["nearestplaces/named"]
277 type = named.attributes["info"].to_s
278 name = named.attributes["name"].to_s
279 description = named.elements["description"].to_s
280 distance = format_distance(place.attributes["approxdistance"].to_i)
281 direction = format_direction((place.attributes["direction"].to_i - 180) % 360)
282 prefix = t "geocoder.description_osm_namefinder.prefix", :distance => distance, :direction => direction, :type => type
283 @results.push({:lat => lat, :lon => lon, :zoom => zoom,
284 :prefix => prefix.capitalize, :name => name,
285 :description => description})
288 render :action => "results"
289 rescue Exception => ex
290 @error = "Error contacting gazetteer.openstreetmap.org: #{ex.to_s}"
291 render :action => "error"
294 def description_geonames
295 # get query parameters
299 # create result array
303 response = fetch_xml("http://ws.geonames.org/countrySubdivision?lat=#{lat}&lng=#{lon}")
306 response.elements.each("geonames/countrySubdivision") do |geoname|
307 name = geoname.get_text("adminName1").to_s
308 country = geoname.get_text("countryName").to_s
309 @results.push({:prefix => "#{name}, #{country}"})
312 render :action => "results"
313 rescue Exception => ex
314 @error = "Error contacting ws.geonames.org: #{ex.to_s}"
315 render :action => "error"
321 return Net::HTTP.get(URI.parse(url))
325 return REXML::Document.new(fetch_text(url))
328 def format_distance(distance)
329 return t("geocoder.distance", :count => distance)
332 def format_direction(bearing)
333 return t("geocoder.direction.south_west") if bearing >= 22.5 and bearing < 67.5
334 return t("geocoder.direction.south") if bearing >= 67.5 and bearing < 112.5
335 return t("geocoder.direction.south_east") if bearing >= 112.5 and bearing < 157.5
336 return t("geocoder.direction.east") if bearing >= 157.5 and bearing < 202.5
337 return t("geocoder.direction.north_east") if bearing >= 202.5 and bearing < 247.5
338 return t("geocoder.direction.north") if bearing >= 247.5 and bearing < 292.5
339 return t("geocoder.direction.north_west") if bearing >= 292.5 and bearing < 337.5
340 return t("geocoder.direction.west")
343 def format_name(name)
344 return name.gsub(/( *\[[^\]]*\])*$/, "")
347 def count_results(results)
350 results.each do |source|
351 count += source[:results].length if source[:results]
357 def escape_query(query)
358 return URI.escape(query, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]", false, 'N'))