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 elsif query.match(/[A-Z]\d[A-Z]\s*\d[A-Z]\d/i)
18 results.push search_ca_postcode(query)
20 results.push search_osm_namefinder(query)
21 results.push search_geonames(query)
24 results_count = count_results(results)
26 render :update do |page|
27 page.replace_html :sidebar_content, :partial => 'results', :object => results
30 position = results.collect { |s| s[:results] }.compact.flatten[0]
31 page.call "setPosition", position[:lat], position[:lon], position[:zoom]
33 page.call "openSidebar"
44 results.push description_osm_namefinder("cities", lat, lon, 2)
45 results.push description_osm_namefinder("towns", lat, lon, 4)
46 results.push description_osm_namefinder("places", lat, lon, 10)
47 results.push description_geonames(lat, lon)
49 render :update do |page|
50 page.replace_html :sidebar_content, :partial => 'results', :object => results
51 page.call "openSidebar"
57 def search_us_postcode(query)
60 # ask geocoder.us (they have a non-commercial use api)
61 response = fetch_text("http://rpc.geocoder.us/service/csv?zip=#{escape_query(query)}")
64 unless response.match(/couldn't find this zip/)
65 data = response.split(/\s*,\s+/) # lat,long,town,state,zip
66 results.push({:lat => data[0], :lon => data[1], :zoom => POSTCODE_ZOOM,
67 :prefix => "#{data[2]}, #{data[3]}, ",
71 return { :source => "Geocoder.us", :url => "http://geocoder.us/", :results => results }
72 rescue Exception => ex
73 return { :source => "Geocoder.us", :url => "http://geocoder.us/", :error => "Error contacting rpc.geocoder.us: #{ex.to_s}" }
76 def search_uk_postcode(query)
79 # ask npemap.org.uk to do a combined npemap + freethepostcode search
80 response = fetch_text("http://www.npemap.org.uk/cgi/geocoder.fcgi?format=text&postcode=#{escape_query(query)}")
83 unless response.match(/Error/)
84 dataline = response.split(/\n/)[1]
85 data = dataline.split(/,/) # easting,northing,postcode,lat,long
86 results.push({:lat => data[3], :lon => data[4], :zoom => POSTCODE_ZOOM,
87 :name => data[2].gsub(/'/, "")})
90 return { :source => "NPEMap / FreeThePostcode", :url => "http://www.npemap.org.uk/", :results => results }
91 rescue Exception => ex
92 return { :source => "NPEMap / FreeThePostcode", :url => "http://www.npemap.org.uk/", :error => "Error contacting www.npemap.org.uk: #{ex.to_s}" }
95 def search_ca_postcode(query)
98 # ask geocoder.ca (note - they have a per-day limit)
99 response = fetch_xml("http://geocoder.ca/?geoit=XML&postal=#{escape_query(query)}")
102 unless response.get_elements("geodata/error")
103 results.push({:lat => response.get_text("geodata/latt").to_s,
104 :lon => response.get_text("geodata/longt").to_s,
105 :zoom => POSTCODE_ZOOM,
106 :name => query.upcase})
109 return { :source => "Geocoder.CA", :url => "http://geocoder.ca/", :results => results }
110 rescue Exception => ex
111 return { :source => "Geocoder.CA", :url => "http://geocoder.ca/", :error => "Error contacting geocoder.ca: #{ex.to_s}" }
114 def search_osm_namefinder(query)
118 response = fetch_xml("http://www.frankieandshadow.com/osm/search.xml?find=#{escape_query(query)}")
121 response.elements.each("searchresults/named") do |named|
122 lat = named.attributes["lat"].to_s
123 lon = named.attributes["lon"].to_s
124 zoom = named.attributes["zoom"].to_s
125 place = named.elements["place/named"] || named.elements["nearestplaces/named"]
126 type = named.attributes["info"].to_s.capitalize
127 name = named.attributes["name"].to_s
128 description = named.elements["description"].to_s
136 distance = format_distance(place.attributes["approxdistance"].to_i)
137 direction = format_direction(place.attributes["direction"].to_i)
138 placename = place.attributes["name"].to_s
139 suffix = ", #{distance} #{direction} of #{placename}"
143 results.push({:lat => lat, :lon => lon, :zoom => zoom,
144 :prefix => prefix, :name => name, :suffix => suffix,
145 :description => description})
148 return { :source => "OpenStreetMap Namefinder", :url => "http://www.frankieandshadow.com/osm/", :results => results }
149 rescue Exception => ex
150 return { :source => "OpenStreetMap Namefinder", :url => "http://www.frankieandshadow.com/osm/", :error => "Error contacting www.frankieandshadow.com: #{ex.to_s}" }
153 def search_geonames(query)
157 response = fetch_xml("http://ws.geonames.org/search?q=#{escape_query(query)}&maxRows=20")
160 response.elements.each("geonames/geoname") do |geoname|
161 lat = geoname.get_text("lat").to_s
162 lon = geoname.get_text("lng").to_s
163 name = geoname.get_text("name").to_s
164 country = geoname.get_text("countryName").to_s
165 results.push({:lat => lat, :lon => lon, :zoom => GEONAMES_ZOOM,
167 :suffix => ", #{country}"})
170 return { :source => "GeoNames", :url => "http://www.geonames.org/", :results => results }
171 rescue Exception => ex
172 return { :source => "GeoNames", :url => "http://www.geonames.org/", :error => "Error contacting ws.geonames.org: #{ex.to_s}" }
175 def description_osm_namefinder(types, lat, lon, max)
179 response = fetch_xml("http://www.frankieandshadow.com/osm/search.xml?find=#{types}+near+#{lat},#{lon}&max=#{max}")
182 response.elements.each("searchresults/named") do |named|
183 lat = named.attributes["lat"].to_s
184 lon = named.attributes["lon"].to_s
185 zoom = named.attributes["zoom"].to_s
186 place = named.elements["place/named"] || named.elements["nearestplaces/named"]
187 type = named.attributes["info"].to_s
188 name = named.attributes["name"].to_s
189 description = named.elements["description"].to_s
190 distance = format_distance(place.attributes["approxdistance"].to_i)
191 direction = format_direction((place.attributes["direction"].to_i - 180) % 360)
192 prefix = "#{distance} #{direction} of #{type} "
193 results.push({:lat => lat, :lon => lon, :zoom => zoom,
194 :prefix => prefix.capitalize, :name => name,
195 :description => description})
198 return { :type => types.capitalize, :source => "OpenStreetMap Namefinder", :url => "http://www.frankieandshadow.com/osm/", :results => results }
199 rescue Exception => ex
200 return { :type => types.capitalize, :source => "OpenStreetMap Namefinder", :url => "http://www.frankieandshadow.com/osm/", :error => "Error contacting www.frankieandshadow.com: #{ex.to_s}" }
203 def description_geonames(lat, lon)
207 response = fetch_xml("http://ws.geonames.org/countrySubdivision?lat=#{lat}&lng=#{lon}")
210 response.elements.each("geonames/countrySubdivision") do |geoname|
211 name = geoname.get_text("adminName1").to_s
212 country = geoname.get_text("countryName").to_s
213 results.push({:prefix => "#{name}, #{country}"})
216 return { :type => "Location", :source => "GeoNames", :url => "http://www.geonames.org/", :results => results }
217 rescue Exception => ex
218 return { :type => types.capitalize, :source => "OpenStreetMap Namefinder", :url => "http://www.frankieandshadow.com/osm/", :error => "Error contacting www.frankieandshadow.com: #{ex.to_s}" }
222 return Net::HTTP.get(URI.parse(url))
226 return REXML::Document.new(fetch_text(url))
229 def format_distance(distance)
230 return "less than 1km" if distance == 0
231 return "about #{distance}km"
234 def format_direction(bearing)
235 return "south-west" if bearing >= 22.5 and bearing < 67.5
236 return "south" if bearing >= 67.5 and bearing < 112.5
237 return "south-east" if bearing >= 112.5 and bearing < 157.5
238 return "east" if bearing >= 157.5 and bearing < 202.5
239 return "north-east" if bearing >= 202.5 and bearing < 247.5
240 return "north" if bearing >= 247.5 and bearing < 292.5
241 return "north-west" if bearing >= 292.5 and bearing < 337.5
245 def count_results(results)
248 results.each do |source|
249 count += source[:results].length if source[:results]
255 def escape_query(query)
256 return URI.escape(query, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]", false, 'N'))