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