1 class GeocoderController < ApplicationController
4 require 'rexml/document'
10 query = params[:query]
13 if query.match(/^\d{5}(-\d{4})?$/)
14 results.push search_us_postcode(query)
15 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)
16 results.push search_uk_postcode(query)
17 results.push search_osm_namefinder(query)
18 elsif query.match(/[A-Z]\d[A-Z]\s*\d[A-Z]\d/i)
19 results.push search_ca_postcode(query)
21 results.push search_osm_namefinder(query)
22 results.push search_geonames(query)
25 results_count = count_results(results)
27 render :update do |page|
28 page.replace_html :sidebar_content, :partial => 'results', :object => results
31 position = results.collect { |s| s[:results] }.compact.flatten[0]
32 page.call "setPosition", position[:lat].to_f, position[:lon].to_f, position[:zoom].to_i
34 page.call "openSidebar"
45 results.push description_osm_namefinder("cities", lat, lon, 2)
46 results.push description_osm_namefinder("towns", lat, lon, 4)
47 results.push description_osm_namefinder("places", lat, lon, 10)
48 results.push description_geonames(lat, lon)
50 render :update do |page|
51 page.replace_html :sidebar_content, :partial => 'results', :object => results
52 page.call "openSidebar"
58 def search_us_postcode(query)
61 # ask geocoder.us (they have a non-commercial use api)
62 response = fetch_text("http://rpc.geocoder.us/service/csv?zip=#{escape_query(query)}")
65 unless response.match(/couldn't find this zip/)
66 data = response.split(/\s*,\s+/) # lat,long,town,state,zip
67 results.push({:lat => data[0], :lon => data[1], :zoom => POSTCODE_ZOOM,
68 :prefix => "#{data[2]}, #{data[3]}, ",
72 return { :source => "Geocoder.us", :url => "http://geocoder.us/", :results => results }
73 rescue Exception => ex
74 return { :source => "Geocoder.us", :url => "http://geocoder.us/", :error => "Error contacting rpc.geocoder.us: #{ex.to_s}" }
77 def search_uk_postcode(query)
80 # ask npemap.org.uk to do a combined npemap + freethepostcode search
81 response = fetch_text("http://www.npemap.org.uk/cgi/geocoder.fcgi?format=text&postcode=#{escape_query(query)}")
84 unless response.match(/Error/)
85 dataline = response.split(/\n/)[1]
86 data = dataline.split(/,/) # easting,northing,postcode,lat,long
87 postcode = data[2].gsub(/'/, "")
88 zoom = POSTCODE_ZOOM - postcode.count("#")
89 results.push({:lat => data[3], :lon => data[4], :zoom => zoom,
93 return { :source => "NPEMap / FreeThePostcode", :url => "http://www.npemap.org.uk/", :results => results }
94 rescue Exception => ex
95 return { :source => "NPEMap / FreeThePostcode", :url => "http://www.npemap.org.uk/", :error => "Error contacting www.npemap.org.uk: #{ex.to_s}" }
98 def search_ca_postcode(query)
101 # ask geocoder.ca (note - they have a per-day limit)
102 response = fetch_xml("http://geocoder.ca/?geoit=XML&postal=#{escape_query(query)}")
105 if response.get_elements("geodata/error").empty?
106 results.push({:lat => response.get_text("geodata/latt").to_s,
107 :lon => response.get_text("geodata/longt").to_s,
108 :zoom => POSTCODE_ZOOM,
109 :name => query.upcase})
112 return { :source => "Geocoder.CA", :url => "http://geocoder.ca/", :results => results }
113 rescue Exception => ex
114 return { :source => "Geocoder.CA", :url => "http://geocoder.ca/", :error => "Error contacting geocoder.ca: #{ex.to_s}" }
117 def search_osm_namefinder(query)
121 response = fetch_xml("http://gazetteer.openstreetmap.org/namefinder/search.xml?find=#{escape_query(query)}")
124 response.elements.each("searchresults/named") do |named|
125 lat = named.attributes["lat"].to_s
126 lon = named.attributes["lon"].to_s
127 zoom = named.attributes["zoom"].to_s
128 place = named.elements["place/named"] || named.elements["nearestplaces/named"]
129 type = named.attributes["info"].to_s.capitalize
130 name = named.attributes["name"].to_s
131 description = named.elements["description"].to_s
141 distance = format_distance(place.attributes["approxdistance"].to_i)
142 direction = format_direction(place.attributes["direction"].to_i)
143 placename = format_name(place.attributes["name"].to_s)
144 suffix = ", #{distance} #{direction} of #{placename}"
146 if place.attributes["rank"].to_i <= 30
151 place.elements.each("nearestplaces/named") do |nearest|
152 nearestrank = nearest.attributes["rank"].to_i
153 nearestscore = nearestrank / nearest.attributes["distance"].to_f
155 if nearestrank > 30 and
156 ( nearestscore > parentscore or
157 ( nearestscore == parentscore and nearestrank > parentrank ) )
159 parentrank = nearestrank
160 parentscore = nearestscore
165 parentname = format_name(parent.attributes["name"].to_s)
167 if place.attributes["info"].to_s == "suburb"
168 suffix = "#{suffix}, #{parentname}"
170 parentdistance = format_distance(parent.attributes["approxdistance"].to_i)
171 parentdirection = format_direction(parent.attributes["direction"].to_i)
172 suffix = "#{suffix} (#{parentdistance} #{parentdirection} of #{parentname})"
180 results.push({:lat => lat, :lon => lon, :zoom => zoom,
181 :prefix => prefix, :name => name, :suffix => suffix,
182 :description => description})
185 return { :source => "OpenStreetMap Namefinder", :url => "http://gazetteer.openstreetmap.org/namefinder/", :results => results }
186 rescue Exception => ex
187 return { :source => "OpenStreetMap Namefinder", :url => "http://gazetteer.openstreetmap.org/namefinder/", :error => "Error contacting gazetteer.openstreetmap.org: #{ex.to_s}" }
190 def search_geonames(query)
194 response = fetch_xml("http://ws.geonames.org/search?q=#{escape_query(query)}&maxRows=20")
197 response.elements.each("geonames/geoname") do |geoname|
198 lat = geoname.get_text("lat").to_s
199 lon = geoname.get_text("lng").to_s
200 name = geoname.get_text("name").to_s
201 country = geoname.get_text("countryName").to_s
202 results.push({:lat => lat, :lon => lon, :zoom => GEONAMES_ZOOM,
204 :suffix => ", #{country}"})
207 return { :source => "GeoNames", :url => "http://www.geonames.org/", :results => results }
208 rescue Exception => ex
209 return { :source => "GeoNames", :url => "http://www.geonames.org/", :error => "Error contacting ws.geonames.org: #{ex.to_s}" }
212 def description_osm_namefinder(types, lat, lon, max)
216 response = fetch_xml("http://gazetteer.openstreetmap.org/namefinder/search.xml?find=#{types}+near+#{lat},#{lon}&max=#{max}")
219 response.elements.each("searchresults/named") do |named|
220 lat = named.attributes["lat"].to_s
221 lon = named.attributes["lon"].to_s
222 zoom = named.attributes["zoom"].to_s
223 place = named.elements["place/named"] || named.elements["nearestplaces/named"]
224 type = named.attributes["info"].to_s
225 name = named.attributes["name"].to_s
226 description = named.elements["description"].to_s
227 distance = format_distance(place.attributes["approxdistance"].to_i)
228 direction = format_direction((place.attributes["direction"].to_i - 180) % 360)
229 prefix = "#{distance} #{direction} of #{type} "
230 results.push({:lat => lat, :lon => lon, :zoom => zoom,
231 :prefix => prefix.capitalize, :name => name,
232 :description => description})
235 return { :type => types.capitalize, :source => "OpenStreetMap Namefinder", :url => "http://gazetteer.openstreetmap.org/namefinder/", :results => results }
236 rescue Exception => ex
237 return { :type => types.capitalize, :source => "OpenStreetMap Namefinder", :url => "http://gazetteer.openstreetmap.org/namefinder/", :error => "Error contacting gazetteer.openstreetmap.org: #{ex.to_s}" }
240 def description_geonames(lat, lon)
244 response = fetch_xml("http://ws.geonames.org/countrySubdivision?lat=#{lat}&lng=#{lon}")
247 response.elements.each("geonames/countrySubdivision") do |geoname|
248 name = geoname.get_text("adminName1").to_s
249 country = geoname.get_text("countryName").to_s
250 results.push({:prefix => "#{name}, #{country}"})
253 return { :type => "Location", :source => "GeoNames", :url => "http://www.geonames.org/", :results => results }
254 rescue Exception => ex
255 return { :type => "Location", :source => "GeoNames", :url => "http://www.geonames.org/", :error => "Error contacting ws.geonames.org: #{ex.to_s}" }
259 return Net::HTTP.get(URI.parse(url))
263 return REXML::Document.new(fetch_text(url))
266 def format_distance(distance)
267 return "less than 1km" if distance == 0
268 return "about #{distance}km"
271 def format_direction(bearing)
272 return "south-west" if bearing >= 22.5 and bearing < 67.5
273 return "south" if bearing >= 67.5 and bearing < 112.5
274 return "south-east" if bearing >= 112.5 and bearing < 157.5
275 return "east" if bearing >= 157.5 and bearing < 202.5
276 return "north-east" if bearing >= 202.5 and bearing < 247.5
277 return "north" if bearing >= 247.5 and bearing < 292.5
278 return "north-west" if bearing >= 292.5 and bearing < 337.5
282 def format_name(name)
283 return name.gsub(/( *\[[^\]]*\])*$/, "")
286 def count_results(results)
289 results.each do |source|
290 count += source[:results].length if source[:results]
296 def escape_query(query)
297 return URI.escape(query, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]", false, 'N'))