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