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_namefinder
136 # get query parameters
137 query = params[:query]
139 # create result array
143 response = fetch_xml("http://gazetteer.openstreetmap.org/namefinder/search.xml?find=#{escape_query(query)}")
146 response.elements.each("searchresults/named") do |named|
147 lat = named.attributes["lat"].to_s
148 lon = named.attributes["lon"].to_s
149 zoom = named.attributes["zoom"].to_s
150 place = named.elements["place/named"] || named.elements["nearestplaces/named"]
151 type = named.attributes["info"].to_s.capitalize
152 name = named.attributes["name"].to_s
153 description = named.elements["description"].to_s
159 prefix = t "geocoder.search_osm_namefinder.prefix", :type => type
163 distance = format_distance(place.attributes["approxdistance"].to_i)
164 direction = format_direction(place.attributes["direction"].to_i)
165 placename = format_name(place.attributes["name"].to_s)
166 suffix = t "geocoder.search_osm_namefinder.suffix_place", :distance => distance, :direction => direction, :placename => placename
168 if place.attributes["rank"].to_i <= 30
173 place.elements.each("nearestplaces/named") do |nearest|
174 nearestrank = nearest.attributes["rank"].to_i
175 nearestscore = nearestrank / nearest.attributes["distance"].to_f
177 if nearestrank > 30 and
178 ( nearestscore > parentscore or
179 ( nearestscore == parentscore and nearestrank > parentrank ) )
181 parentrank = nearestrank
182 parentscore = nearestscore
187 parentname = format_name(parent.attributes["name"].to_s)
189 if place.attributes["info"].to_s == "suburb"
190 suffix = t "geocoder.search_osm_namefinder.suffix_suburb", :suffix => suffix, :parentname => parentname
192 parentdistance = format_distance(parent.attributes["approxdistance"].to_i)
193 parentdirection = format_direction(parent.attributes["direction"].to_i)
194 suffix = t "geocoder.search_osm_namefinder.suffix_parent", :suffix => suffix, :parentdistance => parentdistance, :parentdirection => parentdirection, :parentname => parentname
202 @results.push({:lat => lat, :lon => lon, :zoom => zoom,
203 :prefix => prefix, :name => name, :suffix => suffix,
204 :description => description})
207 render :action => "results"
208 rescue Exception => ex
209 @error = "Error contacting gazetteer.openstreetmap.org: #{ex.to_s}"
210 render :action => "error"
213 def search_osm_nominatim
214 # get query parameters
215 query = params[:query]
216 minlon = params[:minlon]
217 minlat = params[:minlat]
218 maxlon = params[:maxlon]
219 maxlat = params[:maxlat]
222 if minlon && minlat && maxlon && maxlat
223 viewbox = "&viewbox=#{minlon},#{maxlat},#{maxlon},#{minlat}"
226 # get objects to excude
228 exclude = "&exclude_place_ids=#{params[:exclude].join(',')}"
232 response = fetch_xml("#{NOMINATIM_URL}search?format=xml&q=#{escape_query(query)}#{viewbox}#{exclude}&accept-language=#{request.user_preferred_languages.join(',')}")
234 # create result array
237 # create parameter hash for "more results" link
238 @more_params = params.reverse_merge({ :exclude => [] })
240 # extract the results from the response
241 results = response.elements["searchresults"]
244 results.elements.each("place") do |place|
245 lat = place.attributes["lat"].to_s
246 lon = place.attributes["lon"].to_s
247 klass = place.attributes["class"].to_s
248 type = place.attributes["type"].to_s
249 name = place.attributes["display_name"].to_s
250 min_lat,max_lat,min_lon,max_lon = place.attributes["boundingbox"].to_s.split(",")
251 prefix_name = t "geocoder.search_osm_nominatim.prefix.#{klass}.#{type}", :default => type.gsub("_", " ").capitalize
252 prefix = t "geocoder.search_osm_nominatim.prefix_format", :name => prefix_name
254 @results.push({:lat => lat, :lon => lon,
255 :min_lat => min_lat, :max_lat => max_lat,
256 :min_lon => min_lon, :max_lon => max_lon,
257 :prefix => prefix, :name => name})
258 @more_params[:exclude].push(place.attributes["place_id"].to_s)
261 render :action => "results"
262 # rescue Exception => ex
263 # @error = "Error contacting nominatim.openstreetmap.org: #{ex.to_s}"
264 # render :action => "error"
268 # get query parameters
269 query = params[:query]
271 # create result array
275 response = fetch_xml("http://api.geonames.org/search?q=#{escape_query(query)}&maxRows=20&username=#{GEONAMES_USERNAME}")
278 response.elements.each("geonames/geoname") do |geoname|
279 lat = geoname.get_text("lat").to_s
280 lon = geoname.get_text("lng").to_s
281 name = geoname.get_text("name").to_s
282 country = geoname.get_text("countryName").to_s
283 @results.push({:lat => lat, :lon => lon,
284 :zoom => GEONAMES_ZOOM,
286 :suffix => ", #{country}"})
289 render :action => "results"
290 rescue Exception => ex
291 @error = "Error contacting ws.geonames.org: #{ex.to_s}"
292 render :action => "error"
298 @sources.push({ :name => "osm_nominatim" })
299 @sources.push({ :name => "geonames" })
302 def description_osm_namefinder
303 # get query parameters
306 types = params[:types]
309 # create result array
313 response = fetch_xml("http://gazetteer.openstreetmap.org/namefinder/search.xml?find=#{types}+near+#{lat},#{lon}&max=#{max}")
316 response.elements.each("searchresults/named") do |named|
317 lat = named.attributes["lat"].to_s
318 lon = named.attributes["lon"].to_s
319 zoom = named.attributes["zoom"].to_s
320 place = named.elements["place/named"] || named.elements["nearestplaces/named"]
321 type = named.attributes["info"].to_s
322 name = named.attributes["name"].to_s
323 description = named.elements["description"].to_s
324 distance = format_distance(place.attributes["approxdistance"].to_i)
325 direction = format_direction((place.attributes["direction"].to_i - 180) % 360)
326 prefix = t "geocoder.description_osm_namefinder.prefix", :distance => distance, :direction => direction, :type => type
327 @results.push({:lat => lat, :lon => lon, :zoom => zoom,
328 :prefix => prefix.capitalize, :name => name,
329 :description => description})
332 render :action => "results"
333 rescue Exception => ex
334 @error = "Error contacting gazetteer.openstreetmap.org: #{ex.to_s}"
335 render :action => "error"
338 def description_osm_nominatim
339 # get query parameters
344 # create result array
348 response = fetch_xml("#{NOMINATIM_URL}reverse?lat=#{lat}&lon=#{lon}&zoom=#{zoom}&accept-language=#{request.user_preferred_languages.join(',')}")
351 response.elements.each("reversegeocode/result") do |result|
352 description = result.get_text.to_s
354 @results.push({:prefix => "#{description}"})
357 render :action => "results"
358 rescue Exception => ex
359 @error = "Error contacting nominatim.openstreetmap.org: #{ex.to_s}"
360 render :action => "error"
363 def description_geonames
364 # get query parameters
368 # create result array
372 response = fetch_xml("http://ws.geonames.org/countrySubdivision?lat=#{lat}&lng=#{lon}")
375 response.elements.each("geonames/countrySubdivision") do |geoname|
376 name = geoname.get_text("adminName1").to_s
377 country = geoname.get_text("countryName").to_s
378 @results.push({:prefix => "#{name}, #{country}"})
381 render :action => "results"
382 rescue Exception => ex
383 @error = "Error contacting ws.geonames.org: #{ex.to_s}"
384 render :action => "error"
390 return Net::HTTP.get(URI.parse(url))
394 return REXML::Document.new(fetch_text(url))
397 def format_distance(distance)
398 return t("geocoder.distance", :count => distance)
401 def format_direction(bearing)
402 return t("geocoder.direction.south_west") if bearing >= 22.5 and bearing < 67.5
403 return t("geocoder.direction.south") if bearing >= 67.5 and bearing < 112.5
404 return t("geocoder.direction.south_east") if bearing >= 112.5 and bearing < 157.5
405 return t("geocoder.direction.east") if bearing >= 157.5 and bearing < 202.5
406 return t("geocoder.direction.north_east") if bearing >= 202.5 and bearing < 247.5
407 return t("geocoder.direction.north") if bearing >= 247.5 and bearing < 292.5
408 return t("geocoder.direction.north_west") if bearing >= 292.5 and bearing < 337.5
409 return t("geocoder.direction.west")
412 def format_name(name)
413 return name.gsub(/( *\[[^\]]*\])*$/, "")
416 def count_results(results)
419 results.each do |source|
420 count += source[:results].length if source[:results]
426 def escape_query(query)
427 return URI.escape(query, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]", false, 'N'))