Fixed error handling in the name search and tidied things up a bit.
[rails.git] / app / controllers / geocoder_controller.rb
1 class GeocoderController < ApplicationController
2   layout 'site'
3
4   require 'net/http'
5   require 'rexml/document'
6
7   def search
8     if params[:postcode] and not params[:postcode].empty?
9       check_postcode(params[:postcode])
10     elsif params[:query][:postcode] and not params[:query][:postcode].empty?
11       check_postcode(params[:query][:postcode])
12     elsif params[:query][:place_name]  
13       redirect_to :controller => 'geocoder', :action => 'results', :params => {:place_name => params[:query][:place_name]}
14     end 
15   end
16
17   def check_postcode(p)
18
19     @postcode_arr = []
20     postcode = p.upcase
21     escaped_postcode = postcode.sub(/\s/,'%20')
22
23     begin
24       if postcode.match(/(^\d{5}$)|(^\d{5}-\d{4}$)/)
25         # Its a zip code - ask geocoder.us
26         # (They have a non commerical use api)
27         Net::HTTP.start('rpc.geocoder.us') do |http|
28           resp = http.get("/service/csv?zip=#{postcode}")
29           if resp.body.match(/couldn't find this zip/)
30             redirect_to :controller => params[:next_controller], :action => params[:next_action], :error => "invalid_zip_code"
31             return
32           end
33           data = resp.body.split(/, /) # lat,long,town,state,zip
34           lat = data[0] 
35           lon = data[1]
36           redirect_to :controller => params[:next_controller], :action => params[:next_action], :mlat => lat, :mlon => lon, :zoom => 14
37           return
38         end
39       elsif postcode.match(/^([A-Z]{1,2}\d+[A-Z]?\s*\d[A-Z]{2})/)
40         # It matched our naive UK postcode regexp
41         # Ask npemap to do a combined npemap + freethepostcode search
42         Net::HTTP.start('www.npemap.org.uk') do |http|
43           resp = http.get("/cgi/geocoder.fcgi?format=text&postcode=#{escaped_postcode}")
44           dataline = resp.body.split(/\n/)[1]
45           data = dataline.split(/,/) # easting,northing,postcode,lat,long
46           lat = data[3] 
47           lon = data[4]
48           redirect_to :controller => params[:next_controller], :action => params[:next_action], :mlat => lat, :mlon => lon, :zoom => 14
49           return
50         end
51       elsif postcode.match(/^[A-Z]\d[A-Z]\s*\d[A-Z]\d/)
52         # It's a canadian postcode
53         # Ask geocoder.ca (note - they have a per-day limit)
54         postcode = postcode.sub(/\s/,'')
55         Net::HTTP.start('geocoder.ca') do |http|
56           resp = http.get("?geoit=XML&postal=#{postcode}")
57           data_lat = resp.body.slice(/latt>.*?</)
58           data_lon = resp.body.slice(/longt>.*?</)
59           lat = data_lat.split(/[<>]/)[1]
60           lon = data_lon.split(/[<>]/)[1]
61           redirect_to :controller => params[:next_controller], :action => params[:next_action], :mlat => lat, :mlon => lon, :zoom => 14
62           return
63         end
64       elsif postcode.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]) [0-9][ABD-HJLNP-UW-Z]{2})
65         /)
66         #its a UK postcode
67         begin
68           Net::HTTP.start('www.freethepostcode.org') do |http|
69             resp = http.get("/geocode?postcode=#{postcode}")
70             lat = resp.body.scan(/[4-6][0-9]\.?[0-9]+/)
71             lon = resp.body.scan(/[-+][0-9]\.?[0-9]+/)
72             redirect_to :controller => params[:next_controller], :action => params[:next_action], :mlat => lat, :mlon => lon, :zoom => 14
73             return
74           end
75         rescue
76           redirect_to :controller => params[:next_controller], :action => params[:next_action], :error => "invalid_postcode"
77           #redirect to somewhere else
78         end
79       elsif
80         # Some other postcode / zip code
81         # Throw it at geonames, and see if they have any luck with it
82         Net::HTTP.start('ws.geonames.org') do |http|
83           resp = http.get("/postalCodeSearch?postalcode=#{escaped_postcode}&maxRows=1")
84           hits = resp.body.slice(/totalResultsCount>.*?</).split(/[<>]/)[1]
85           if hits == "0"
86             # Geonames doesn't know, it's probably wrong
87             redirect_to :controller => params[:next_controller], :action => params[:next_action], :error => "invalid_postcode_or_zip"
88             return
89           end
90           data_lat = resp.body.slice(/lat>.*?</)
91           data_lon = resp.body.slice(/lng>.*?</)
92           lat = data_lat.split(/[<>]/)[1]
93           lon = data_lon.split(/[<>]/)[1]
94           redirect_to :controller => params[:next_controller], :action => params[:next_action], :mlat => lat, :mlon => lon, :zoom => 14
95         end
96       else
97         # Some other postcode / zip file
98         redirect_to :controller => params[:next_controller], :action => params[:next_action], :error => "invalid_postcode_or_zip"
99         return
100       end
101     rescue
102       #Its likely that an api is down
103       redirect_to :controller => params[:next_controller], :action => params[:next_action], :error => "api_down"
104     end
105   end
106
107   def results
108     @place_name = params[:place_name]
109     res_hash = {}
110     @res_ary = []
111     begin
112       Net::HTTP.start('ws.geonames.org') do |http|
113         res = http.get("/search?q=#{@place_name}&maxRows=10")
114         xml = REXML::Document.new(res.body)
115         xml.elements.each("geonames/geoname") do |ele|
116           res_hash = {}
117           ele.elements.each("name"){ |n| res_hash['name'] = n.text }
118           ele.elements.each("countryCode"){ |n| res_hash['countrycode'] = n.text }
119           ele.elements.each("countryName"){ |n| res_hash['countryname'] = n.text }
120           ele.elements.each("lat"){ |n| res_hash['lat'] = n.text }
121           ele.elements.each("lng"){ |n| res_hash['lon']= n.text }
122           @res_ary << res_hash
123         end 
124       end
125
126       flash.delete(:notice)
127     rescue Timeout::Error
128       flash[:notice] = "Timed out waiting for results from ws.geonames.org"
129     rescue Exception => ex
130       flash[:notice] = "Error contacting ws.geonames.org: #{ex.to_s}"
131     end
132   end
133 end