Support zip codes
[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     res_hash = {}
9     @postcode_arr = []
10     @res_ary = []
11
12     if params[:query][:postcode] 
13       postcode = params[:query][:postcode]
14       escaped_postcode = postcode.sub(/\s/,'%20')
15
16       if postcode.match(/(^\d{5}$)|(^\d{5}-\d{4}$)/)
17         # Its a zip code - ask geocoder.us
18         # (They have a non commerical use api)
19         Net::HTTP.start('rpc.geocoder.us') do |http|
20           resp = http.get("/service/csv?zip=#{postcode}")
21           data = resp.body.split(/, /) # lat,long,town,state,zip
22           lat = data[0] 
23           lon = data[1]
24           redirect_to "/index.html?lat=#{lat}&lon=#{lon}&zoom=14"
25         end
26       elsif postcode.match(/^(\w{1,2}\d+\w?\s*\d\w\w)/)
27         # It matched our naive UK postcode regexp
28         # Ask npemap to do a combined npemap + freethepostcode search
29         Net::HTTP.start('www.npemap.org.uk') do |http|
30           resp = http.get("/cgi/geocoder.fcgi?format=text&postcode=#{escaped_postcode}")
31           dataline = resp.body.split(/\n/)[1]
32           data = dataline.split(/,/) # easting,northing,postcode,lat,long
33           lat = data[3] 
34           lon = data[4]
35           redirect_to "/index.html?lat=#{lat}&lon=#{lon}&zoom=14"
36         end
37       else
38         # Some other postcode / zip file
39         redirect_to "/index.html?error=unknown_postcode_or_zip"
40       end
41     else
42       if params[:query][:place_name] != nil or "" 
43         place_name = params[:query][:place_name]
44         Net::HTTP.start('ws.geonames.org') do |http|
45           res = http.get("/search?q=#{place_name}&maxRows=10")
46           xml = REXML::Document.new(res.body)
47           xml.elements.each("geonames/geoname") do |ele|
48             res_hash = {}
49             ele.elements.each("name"){ |n| res_hash['name'] = n.text }
50             ele.elements.each("countryCode"){ |n| res_hash['country_code'] = n.text }
51             ele.elements.each("countryNode"){ |n| res_hash['country_name'] = n.text }
52             ele.elements.each("lat"){ |n| res_hash['lat'] = n.text }
53             ele.elements.each("lng"){ |n| res_hash['lon']= n.text }
54             @res_ary << res_hash
55           end 
56         end
57       end
58       redirect_to :controller => 'geocoder', :action => 'results', :params => @res_ary
59     end
60   end
61
62   def result
63     @res = :params[@res_ary]
64   end
65 end