now you can search openstreetmap.org/postcode/wc1e6bt
[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 "/index.html?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 "/index.html?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 "/index.html?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 "/index.html?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 "/index.html?mlat=#{lat}&mlon=#{lon}&zoom=14"
85             return
86           end
87         rescue
88           redirect_to "/index.html"
89           #redirect to somewhere else
90         end
91         redirect_to "/index.html?mlat=#{lat}&mlon=#{lon}&zoom=14"
92         #redirect_to "/index.html?error=unknown_postcode_or_zip"
93       elsif
94         # Some other postcode / zip code
95         # Throw it at geonames, and see if they have any luck with it
96         Net::HTTP.start('ws.geonames.org') do |http|
97           resp = http.get("/postalCodeSearch?postalcode=#{escaped_postcode}&maxRows=1")
98           hits = resp.body.slice(/totalResultsCount>.*?</).split(/[<>]/)[1]
99           if hits == "0"
100             # Geonames doesn't know, it's probably wrong
101             redirect_to "/index.html?error=unknown_postcode_or_zip"
102             return
103           end
104           data_lat = resp.body.slice(/lat>.*?</)
105           data_lon = resp.body.slice(/lng>.*?</)
106           lat = data_lat.split(/[<>]/)[1]
107           lon = data_lon.split(/[<>]/)[1]
108           redirect_to "/index.html?mlat=#{lat}&mlon=#{lon}&zoom=14"
109         end
110       else
111         # Some other postcode / zip file
112         redirect_to "/index.html?error=unknown_postcode_or_zip"
113         return
114       end
115     rescue
116       #Its likely that an api is down
117       redirect_to "/index.html?error=api_dpwn"
118     end
119   end
120
121   def results
122     @place_name = params[:place_name]
123     res_hash = {}
124     @res_ary = []
125     begin
126       Net::HTTP.start('ws.geonames.org') do |http|
127         res = http.get("/search?q=#{@place_name}&maxRows=10")
128         xml = REXML::Document.new(res.body)
129         xml.elements.each("geonames/geoname") do |ele|
130           res_hash = {}
131           ele.elements.each("name"){ |n| res_hash['name'] = n.text }
132           ele.elements.each("countryCode"){ |n| res_hash['countrycode'] = n.text }
133           ele.elements.each("countryName"){ |n| res_hash['countryname'] = n.text }
134           ele.elements.each("lat"){ |n| res_hash['lat'] = n.text }
135           ele.elements.each("lng"){ |n| res_hash['lon']= n.text }
136           @res_ary << res_hash
137         end 
138       end
139     rescue
140       #Flash a notice to say that geonames is broken
141       redirect_to "/index.html"
142     end
143   end
144 end