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 elsif @query.match(/^[A-Z]\d[A-Z]\s*\d[A-Z]\d$/i)
24 @sources.push "ca_postcode"
26 @sources.push "osm_nominatim"
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"
216 def search_osm_nominatim
217 # get query parameters
218 query = params[:query]
219 minlon = params[:minlon]
220 minlat = params[:minlat]
221 maxlon = params[:maxlon]
222 maxlat = params[:maxlat]
225 if minlon && minlat && maxlon && maxlat
226 viewbox = "&viewbox=#{minlon},#{maxlat},#{maxlon},#{minlat}"
229 # get objects to excude
231 exclude = "&exclude_place_ids=#{params[:exclude].join(',')}"
235 response = fetch_xml("http://nominatim.openstreetmap.org/search?format=xml&q=#{escape_query(query)}#{viewbox}#{exclude}&accept-language=#{request.user_preferred_languages.join(',')}")
237 # create result array
240 # create parameter hash for "more results" link
241 @more_params = params.reverse_merge({ :exclude => [] })
243 # extract the results from the response
244 results = response.elements["searchresults"]
247 results.elements.each("place") do |place|
248 lat = place.attributes["lat"].to_s
249 lon = place.attributes["lon"].to_s
250 klass = place.attributes["class"].to_s
251 type = place.attributes["type"].to_s
252 name = place.attributes["display_name"].to_s
253 min_lat,max_lat,min_lon,max_lon = place.attributes["boundingbox"].to_s.split(",")
254 prefix = t "geocoder.search_osm_nominatim.prefix.#{klass}.#{type}", :default => type.gsub("_", " ").capitalize
256 @results.push({:lat => lat, :lon => lon,
257 :min_lat => min_lat, :max_lat => max_lat,
258 :min_lon => min_lon, :max_lon => max_lon,
259 :prefix => prefix, :name => name})
260 @more_params[:exclude].push(place.attributes["place_id"].to_s)
263 render :action => "results"
264 rescue Exception => ex
265 @error = "Error contacting nominatim.openstreetmap.org: #{ex.to_s}"
266 render :action => "error"
270 # get query parameters
271 query = params[:query]
273 # create result array
277 response = fetch_xml("http://ws.geonames.org/search?q=#{escape_query(query)}&maxRows=20")
280 response.elements.each("geonames/geoname") do |geoname|
281 lat = geoname.get_text("lat").to_s
282 lon = geoname.get_text("lng").to_s
283 name = geoname.get_text("name").to_s
284 country = geoname.get_text("countryName").to_s
285 @results.push({:lat => lat, :lon => lon,
286 :zoom => APP_CONFIG['geonames_zoom'],
288 :suffix => ", #{country}"})
291 render :action => "results"
292 rescue Exception => ex
293 @error = "Error contacting ws.geonames.org: #{ex.to_s}"
294 render :action => "error"
300 @sources.push({ :name => "osm_nominatim" })
301 @sources.push({ :name => "geonames" })
303 render :update do |page|
304 page.replace_html :sidebar_content, :partial => "description"
305 page.call "openSidebar"
309 def description_osm_namefinder
310 # get query parameters
313 types = params[:types]
316 # create result array
320 response = fetch_xml("http://gazetteer.openstreetmap.org/namefinder/search.xml?find=#{types}+near+#{lat},#{lon}&max=#{max}")
323 response.elements.each("searchresults/named") do |named|
324 lat = named.attributes["lat"].to_s
325 lon = named.attributes["lon"].to_s
326 zoom = named.attributes["zoom"].to_s
327 place = named.elements["place/named"] || named.elements["nearestplaces/named"]
328 type = named.attributes["info"].to_s
329 name = named.attributes["name"].to_s
330 description = named.elements["description"].to_s
331 distance = format_distance(place.attributes["approxdistance"].to_i)
332 direction = format_direction((place.attributes["direction"].to_i - 180) % 360)
333 prefix = t "geocoder.description_osm_namefinder.prefix", :distance => distance, :direction => direction, :type => type
334 @results.push({:lat => lat, :lon => lon, :zoom => zoom,
335 :prefix => prefix.capitalize, :name => name,
336 :description => description})
339 render :action => "results"
340 rescue Exception => ex
341 @error = "Error contacting gazetteer.openstreetmap.org: #{ex.to_s}"
342 render :action => "error"
345 def description_osm_nominatim
346 # get query parameters
351 # create result array
355 response = fetch_xml("http://nominatim.openstreetmap.org/reverse?lat=#{lat}&lon=#{lon}&zoom=#{zoom}&accept-language=#{request.user_preferred_languages.join(',')}")
358 response.elements.each("reversegeocode") do |result|
359 description = result.get_text("result").to_s
361 @results.push({:prefix => "#{description}"})
364 render :action => "results"
365 rescue Exception => ex
366 @error = "Error contacting nominatim.openstreetmap.org: #{ex.to_s}"
367 render :action => "error"
370 def description_geonames
371 # get query parameters
375 # create result array
379 response = fetch_xml("http://ws.geonames.org/countrySubdivision?lat=#{lat}&lng=#{lon}")
382 response.elements.each("geonames/countrySubdivision") do |geoname|
383 name = geoname.get_text("adminName1").to_s
384 country = geoname.get_text("countryName").to_s
385 @results.push({:prefix => "#{name}, #{country}"})
388 render :action => "results"
389 rescue Exception => ex
390 @error = "Error contacting ws.geonames.org: #{ex.to_s}"
391 render :action => "error"
397 return Net::HTTP.get(URI.parse(url))
401 return REXML::Document.new(fetch_text(url))
404 def format_distance(distance)
405 return t("geocoder.distance", :count => distance)
408 def format_direction(bearing)
409 return t("geocoder.direction.south_west") if bearing >= 22.5 and bearing < 67.5
410 return t("geocoder.direction.south") if bearing >= 67.5 and bearing < 112.5
411 return t("geocoder.direction.south_east") if bearing >= 112.5 and bearing < 157.5
412 return t("geocoder.direction.east") if bearing >= 157.5 and bearing < 202.5
413 return t("geocoder.direction.north_east") if bearing >= 202.5 and bearing < 247.5
414 return t("geocoder.direction.north") if bearing >= 247.5 and bearing < 292.5
415 return t("geocoder.direction.north_west") if bearing >= 292.5 and bearing < 337.5
416 return t("geocoder.direction.west")
419 def format_name(name)
420 return name.gsub(/( *\[[^\]]*\])*$/, "")
423 def count_results(results)
426 results.each do |source|
427 count += source[:results].length if source[:results]
433 def escape_query(query)
434 return URI.escape(query, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]", false, 'N'))