1 class GeocoderController < ApplicationController
4 require 'rexml/document'
6 before_filter :set_locale
15 if query.match(/^[+-]?\d+(\.\d*)?\s*[\s,]\s*[+-]?\d+(\.\d*)?$/)
16 results.push search_latlon(query)
17 elsif query.match(/^\d{5}(-\d{4})?$/)
18 results.push search_us_postcode(query)
19 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)
20 results.push search_uk_postcode(query)
21 results.push search_osm_namefinder(query)
22 elsif query.match(/^[A-Z]\d[A-Z]\s*\d[A-Z]\d$/i)
23 results.push search_ca_postcode(query)
25 results.push search_osm_namefinder(query)
26 results.push search_geonames(query)
29 results_count = count_results(results)
31 render :update do |page|
32 page.replace_html :sidebar_content, :partial => 'results', :object => results
35 position = results.collect { |s| s[:results] }.compact.flatten[0]
36 page.call "setPosition", position[:lat].to_f, position[:lon].to_f, position[:zoom].to_i
38 page.call "openSidebar"
49 results.push description_osm_namefinder("cities", lat, lon, 2)
50 results.push description_osm_namefinder("towns", lat, lon, 4)
51 results.push description_osm_namefinder("places", lat, lon, 10)
52 results.push description_geonames(lat, lon)
54 render :update do |page|
55 page.replace_html :sidebar_content, :partial => 'results', :object => results
56 page.call "openSidebar"
62 def search_latlon(query)
66 if m = query.match(/^([+-]?\d+(\.\d*)?)\s*[\s,]\s*([+-]?\d+(\.\d*)?)$/)
72 if lat < -90 or lat > 90
73 return { :source => "Internal", :url => "http://openstreetmap.org/", :error => "Latitude #{lat} out of range" }
74 elsif lon < -180 or lon > 180
75 return { :source => "Internal", :url => "http://openstreetmap.org/", :error => "Longitude #{lon} out of range" }
77 results.push({:lat => lat, :lon => lon,
78 :zoom => APP_CONFIG['postcode_zoom'],
79 :name => "#{lat}, #{lon}"})
81 return { :source => "Internal", :url => "http://openstreetmap.org/", :results => results }
85 def search_us_postcode(query)
88 # ask geocoder.us (they have a non-commercial use api)
89 response = fetch_text("http://rpc.geocoder.us/service/csv?zip=#{escape_query(query)}")
92 unless response.match(/couldn't find this zip/)
93 data = response.split(/\s*,\s+/) # lat,long,town,state,zip
94 results.push({:lat => data[0], :lon => data[1],
95 :zoom => APP_CONFIG['postcode_zoom'],
96 :prefix => "#{data[2]}, #{data[3]}, ",
100 return { :source => "Geocoder.us", :url => "http://geocoder.us/", :results => results }
101 rescue Exception => ex
102 return { :source => "Geocoder.us", :url => "http://geocoder.us/", :error => "Error contacting rpc.geocoder.us: #{ex.to_s}" }
105 def search_uk_postcode(query)
108 # ask npemap.org.uk to do a combined npemap + freethepostcode search
109 response = fetch_text("http://www.npemap.org.uk/cgi/geocoder.fcgi?format=text&postcode=#{escape_query(query)}")
112 unless response.match(/Error/)
113 dataline = response.split(/\n/)[1]
114 data = dataline.split(/,/) # easting,northing,postcode,lat,long
115 postcode = data[2].gsub(/'/, "")
116 zoom = APP_CONFIG['postcode_zoom'] - postcode.count("#")
117 results.push({:lat => data[3], :lon => data[4], :zoom => zoom,
121 return { :source => "NPEMap / FreeThePostcode", :url => "http://www.npemap.org.uk/", :results => results }
122 rescue Exception => ex
123 return { :source => "NPEMap / FreeThePostcode", :url => "http://www.npemap.org.uk/", :error => "Error contacting www.npemap.org.uk: #{ex.to_s}" }
126 def search_ca_postcode(query)
129 # ask geocoder.ca (note - they have a per-day limit)
130 response = fetch_xml("http://geocoder.ca/?geoit=XML&postal=#{escape_query(query)}")
133 if response.get_elements("geodata/error").empty?
134 results.push({:lat => response.get_text("geodata/latt").to_s,
135 :lon => response.get_text("geodata/longt").to_s,
136 :zoom => APP_CONFIG['postcode_zoom'],
137 :name => query.upcase})
140 return { :source => "Geocoder.CA", :url => "http://geocoder.ca/", :results => results }
141 rescue Exception => ex
142 return { :source => "Geocoder.CA", :url => "http://geocoder.ca/", :error => "Error contacting geocoder.ca: #{ex.to_s}" }
145 def search_osm_namefinder(query)
149 response = fetch_xml("http://gazetteer.openstreetmap.org/namefinder/search.xml?find=#{escape_query(query)}")
152 response.elements.each("searchresults/named") do |named|
153 lat = named.attributes["lat"].to_s
154 lon = named.attributes["lon"].to_s
155 zoom = named.attributes["zoom"].to_s
156 place = named.elements["place/named"] || named.elements["nearestplaces/named"]
157 type = named.attributes["info"].to_s.capitalize
158 name = named.attributes["name"].to_s
159 description = named.elements["description"].to_s
169 distance = format_distance(place.attributes["approxdistance"].to_i)
170 direction = format_direction(place.attributes["direction"].to_i)
171 placename = format_name(place.attributes["name"].to_s)
172 suffix = ", #{distance} #{direction} of #{placename}"
174 if place.attributes["rank"].to_i <= 30
179 place.elements.each("nearestplaces/named") do |nearest|
180 nearestrank = nearest.attributes["rank"].to_i
181 nearestscore = nearestrank / nearest.attributes["distance"].to_f
183 if nearestrank > 30 and
184 ( nearestscore > parentscore or
185 ( nearestscore == parentscore and nearestrank > parentrank ) )
187 parentrank = nearestrank
188 parentscore = nearestscore
193 parentname = format_name(parent.attributes["name"].to_s)
195 if place.attributes["info"].to_s == "suburb"
196 suffix = "#{suffix}, #{parentname}"
198 parentdistance = format_distance(parent.attributes["approxdistance"].to_i)
199 parentdirection = format_direction(parent.attributes["direction"].to_i)
200 suffix = "#{suffix} (#{parentdistance} #{parentdirection} of #{parentname})"
208 results.push({:lat => lat, :lon => lon, :zoom => zoom,
209 :prefix => prefix, :name => name, :suffix => suffix,
210 :description => description})
213 return { :source => "OpenStreetMap Namefinder", :url => "http://gazetteer.openstreetmap.org/namefinder/", :results => results }
214 rescue Exception => ex
215 return { :source => "OpenStreetMap Namefinder", :url => "http://gazetteer.openstreetmap.org/namefinder/", :error => "Error contacting gazetteer.openstreetmap.org: #{ex.to_s}" }
218 def search_geonames(query)
222 response = fetch_xml("http://ws.geonames.org/search?q=#{escape_query(query)}&maxRows=20")
225 response.elements.each("geonames/geoname") do |geoname|
226 lat = geoname.get_text("lat").to_s
227 lon = geoname.get_text("lng").to_s
228 name = geoname.get_text("name").to_s
229 country = geoname.get_text("countryName").to_s
230 results.push({:lat => lat, :lon => lon,
231 :zoom => APP_CONFIG['geonames_zoom'],
233 :suffix => ", #{country}"})
236 return { :source => "GeoNames", :url => "http://www.geonames.org/", :results => results }
237 rescue Exception => ex
238 return { :source => "GeoNames", :url => "http://www.geonames.org/", :error => "Error contacting ws.geonames.org: #{ex.to_s}" }
241 def description_osm_namefinder(types, lat, lon, max)
245 response = fetch_xml("http://gazetteer.openstreetmap.org/namefinder/search.xml?find=#{types}+near+#{lat},#{lon}&max=#{max}")
248 response.elements.each("searchresults/named") do |named|
249 lat = named.attributes["lat"].to_s
250 lon = named.attributes["lon"].to_s
251 zoom = named.attributes["zoom"].to_s
252 place = named.elements["place/named"] || named.elements["nearestplaces/named"]
253 type = named.attributes["info"].to_s
254 name = named.attributes["name"].to_s
255 description = named.elements["description"].to_s
256 distance = format_distance(place.attributes["approxdistance"].to_i)
257 direction = format_direction((place.attributes["direction"].to_i - 180) % 360)
258 prefix = "#{distance} #{direction} of #{type} "
259 results.push({:lat => lat, :lon => lon, :zoom => zoom,
260 :prefix => prefix.capitalize, :name => name,
261 :description => description})
264 return { :type => types.capitalize, :source => "OpenStreetMap Namefinder", :url => "http://gazetteer.openstreetmap.org/namefinder/", :results => results }
265 rescue Exception => ex
266 return { :type => types.capitalize, :source => "OpenStreetMap Namefinder", :url => "http://gazetteer.openstreetmap.org/namefinder/", :error => "Error contacting gazetteer.openstreetmap.org: #{ex.to_s}" }
269 def description_geonames(lat, lon)
273 response = fetch_xml("http://ws.geonames.org/countrySubdivision?lat=#{lat}&lng=#{lon}")
276 response.elements.each("geonames/countrySubdivision") do |geoname|
277 name = geoname.get_text("adminName1").to_s
278 country = geoname.get_text("countryName").to_s
279 results.push({:prefix => "#{name}, #{country}"})
282 return { :type => "Location", :source => "GeoNames", :url => "http://www.geonames.org/", :results => results }
283 rescue Exception => ex
284 return { :type => "Location", :source => "GeoNames", :url => "http://www.geonames.org/", :error => "Error contacting ws.geonames.org: #{ex.to_s}" }
288 return Net::HTTP.get(URI.parse(url))
292 return REXML::Document.new(fetch_text(url))
295 def format_distance(distance)
296 return "less than 1km" if distance == 0
297 return "about #{distance}km"
300 def format_direction(bearing)
301 return "south-west" if bearing >= 22.5 and bearing < 67.5
302 return "south" if bearing >= 67.5 and bearing < 112.5
303 return "south-east" if bearing >= 112.5 and bearing < 157.5
304 return "east" if bearing >= 157.5 and bearing < 202.5
305 return "north-east" if bearing >= 202.5 and bearing < 247.5
306 return "north" if bearing >= 247.5 and bearing < 292.5
307 return "north-west" if bearing >= 292.5 and bearing < 337.5
311 def format_name(name)
312 return name.gsub(/( *\[[^\]]*\])*$/, "")
315 def count_results(results)
318 results.each do |source|
319 count += source[:results].length if source[:results]
325 def escape_query(query)
326 return URI.escape(query, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]", false, 'N'))