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], position[:lon], position[:zoom]
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 results.push({:lat => data[3], :lon => data[4], :zoom => POSTCODE_ZOOM,
88 :name => data[2].gsub(/'/, "")})
91 return { :source => "NPEMap / FreeThePostcode", :url => "http://www.npemap.org.uk/", :results => results }
92 rescue Exception => ex
93 return { :source => "NPEMap / FreeThePostcode", :url => "http://www.npemap.org.uk/", :error => "Error contacting www.npemap.org.uk: #{ex.to_s}" }
96 def search_ca_postcode(query)
99 # ask geocoder.ca (note - they have a per-day limit)
100 response = fetch_xml("http://geocoder.ca/?geoit=XML&postal=#{escape_query(query)}")
103 unless response.get_elements("geodata/error")
104 results.push({:lat => response.get_text("geodata/latt").to_s,
105 :lon => response.get_text("geodata/longt").to_s,
106 :zoom => POSTCODE_ZOOM,
107 :name => query.upcase})
110 return { :source => "Geocoder.CA", :url => "http://geocoder.ca/", :results => results }
111 rescue Exception => ex
112 return { :source => "Geocoder.CA", :url => "http://geocoder.ca/", :error => "Error contacting geocoder.ca: #{ex.to_s}" }
115 def search_osm_namefinder(query)
119 response = fetch_xml("http://www.frankieandshadow.com/osm/search.xml?find=#{escape_query(query)}")
122 response.elements.each("searchresults/named") do |named|
123 lat = named.attributes["lat"].to_s
124 lon = named.attributes["lon"].to_s
125 zoom = named.attributes["zoom"].to_s
126 place = named.elements["place/named"] || named.elements["nearestplaces/named"]
127 type = named.attributes["info"].to_s.capitalize
128 name = named.attributes["name"].to_s
129 description = named.elements["description"].to_s
137 distance = format_distance(place.attributes["approxdistance"].to_i)
138 direction = format_direction(place.attributes["direction"].to_i)
139 placename = place.attributes["name"].to_s
140 suffix = ", #{distance} #{direction} of #{placename}"
144 results.push({:lat => lat, :lon => lon, :zoom => zoom,
145 :prefix => prefix, :name => name, :suffix => suffix,
146 :description => description})
149 return { :source => "OpenStreetMap Namefinder", :url => "http://www.frankieandshadow.com/osm/", :results => results }
150 rescue Exception => ex
151 return { :source => "OpenStreetMap Namefinder", :url => "http://www.frankieandshadow.com/osm/", :error => "Error contacting www.frankieandshadow.com: #{ex.to_s}" }
154 def search_geonames(query)
158 response = fetch_xml("http://ws.geonames.org/search?q=#{escape_query(query)}&maxRows=20")
161 response.elements.each("geonames/geoname") do |geoname|
162 lat = geoname.get_text("lat").to_s
163 lon = geoname.get_text("lng").to_s
164 name = geoname.get_text("name").to_s
165 country = geoname.get_text("countryName").to_s
166 results.push({:lat => lat, :lon => lon, :zoom => GEONAMES_ZOOM,
168 :suffix => ", #{country}"})
171 return { :source => "GeoNames", :url => "http://www.geonames.org/", :results => results }
172 rescue Exception => ex
173 return { :source => "GeoNames", :url => "http://www.geonames.org/", :error => "Error contacting ws.geonames.org: #{ex.to_s}" }
176 def description_osm_namefinder(types, lat, lon, max)
180 response = fetch_xml("http://www.frankieandshadow.com/osm/search.xml?find=#{types}+near+#{lat},#{lon}&max=#{max}")
183 response.elements.each("searchresults/named") do |named|
184 lat = named.attributes["lat"].to_s
185 lon = named.attributes["lon"].to_s
186 zoom = named.attributes["zoom"].to_s
187 place = named.elements["place/named"] || named.elements["nearestplaces/named"]
188 type = named.attributes["info"].to_s
189 name = named.attributes["name"].to_s
190 description = named.elements["description"].to_s
191 distance = format_distance(place.attributes["approxdistance"].to_i)
192 direction = format_direction((place.attributes["direction"].to_i - 180) % 360)
193 prefix = "#{distance} #{direction} of #{type} "
194 results.push({:lat => lat, :lon => lon, :zoom => zoom,
195 :prefix => prefix.capitalize, :name => name,
196 :description => description})
199 return { :type => types.capitalize, :source => "OpenStreetMap Namefinder", :url => "http://www.frankieandshadow.com/osm/", :results => results }
200 rescue Exception => ex
201 return { :type => types.capitalize, :source => "OpenStreetMap Namefinder", :url => "http://www.frankieandshadow.com/osm/", :error => "Error contacting www.frankieandshadow.com: #{ex.to_s}" }
204 def description_geonames(lat, lon)
208 response = fetch_xml("http://ws.geonames.org/countrySubdivision?lat=#{lat}&lng=#{lon}")
211 response.elements.each("geonames/countrySubdivision") do |geoname|
212 name = geoname.get_text("adminName1").to_s
213 country = geoname.get_text("countryName").to_s
214 results.push({:prefix => "#{name}, #{country}"})
217 return { :type => "Location", :source => "GeoNames", :url => "http://www.geonames.org/", :results => results }
218 rescue Exception => ex
219 return { :type => types.capitalize, :source => "OpenStreetMap Namefinder", :url => "http://www.frankieandshadow.com/osm/", :error => "Error contacting www.frankieandshadow.com: #{ex.to_s}" }
223 return Net::HTTP.get(URI.parse(url))
227 return REXML::Document.new(fetch_text(url))
230 def format_distance(distance)
231 return "less than 1km" if distance == 0
232 return "about #{distance}km"
235 def format_direction(bearing)
236 return "south-west" if bearing >= 22.5 and bearing < 67.5
237 return "south" if bearing >= 67.5 and bearing < 112.5
238 return "south-east" if bearing >= 112.5 and bearing < 157.5
239 return "east" if bearing >= 157.5 and bearing < 202.5
240 return "north-east" if bearing >= 202.5 and bearing < 247.5
241 return "north" if bearing >= 247.5 and bearing < 292.5
242 return "north-west" if bearing >= 292.5 and bearing < 337.5
246 def count_results(results)
249 results.each do |source|
250 count += source[:results].length if source[:results]
256 def escape_query(query)
257 return URI.escape(query, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]", false, 'N'))