Support zip codes
[rails.git] / app / controllers / geocoder_controller.rb
index 99042414d1f24a93241159c72ef78a7cfdf5e493..22b1a8b3ff11759aed811fbddea85e6c8deb68e5 100644 (file)
@@ -4,26 +4,39 @@ class GeocoderController < ApplicationController
   require 'net/http'
   require 'rexml/document'
 
   require 'net/http'
   require 'rexml/document'
 
-  before_filter :authorize_web
-  before_filter :require_user
-
   def search
     res_hash = {}
     @postcode_arr = []
     @res_ary = []
 
   def search
     res_hash = {}
     @postcode_arr = []
     @res_ary = []
 
-    if params[:query][:postcode] != "" 
+    if params[:query][:postcode] 
       postcode = params[:query][:postcode]
       postcode = params[:query][:postcode]
+      escaped_postcode = postcode.sub(/\s/,'%20')
+
       if postcode.match(/(^\d{5}$)|(^\d{5}-\d{4}$)/)
       if postcode.match(/(^\d{5}$)|(^\d{5}-\d{4}$)/)
-        #its a zip code - do something
-      else
-        Net::HTTP.start('www.freethepostcode.org') do |http|
-          resp = http.get("/geocode?postcode=#{postcode}")
-          lat = resp.body.scan(/[4-6][0-9]\.?[0-9]+/)
-          lon = resp.body.scan(/[-+][0-9]\.?[0-9]+/)
-          @postcode_array = [lat, lon]
-          redirect_to "/index.html?lat=#{@postcode_array[0]}&lon=#{@postcode_array[1]}&zoom=14"
+        # Its a zip code - ask geocoder.us
+        # (They have a non commerical use api)
+        Net::HTTP.start('rpc.geocoder.us') do |http|
+          resp = http.get("/service/csv?zip=#{postcode}")
+          data = resp.body.split(/, /) # lat,long,town,state,zip
+          lat = data[0] 
+          lon = data[1]
+          redirect_to "/index.html?lat=#{lat}&lon=#{lon}&zoom=14"
         end
         end
+      elsif postcode.match(/^(\w{1,2}\d+\w?\s*\d\w\w)/)
+        # It matched our naive UK postcode regexp
+        # Ask npemap to do a combined npemap + freethepostcode search
+        Net::HTTP.start('www.npemap.org.uk') do |http|
+          resp = http.get("/cgi/geocoder.fcgi?format=text&postcode=#{escaped_postcode}")
+          dataline = resp.body.split(/\n/)[1]
+          data = dataline.split(/,/) # easting,northing,postcode,lat,long
+          lat = data[3] 
+          lon = data[4]
+          redirect_to "/index.html?lat=#{lat}&lon=#{lon}&zoom=14"
+        end
+      else
+        # Some other postcode / zip file
+        redirect_to "/index.html?error=unknown_postcode_or_zip"
       end
     else
       if params[:query][:place_name] != nil or "" 
       end
     else
       if params[:query][:place_name] != nil or "" 
@@ -42,11 +55,11 @@ class GeocoderController < ApplicationController
           end 
         end
       end
           end 
         end
       end
-      redirect_to :controller => 'geocoder', :action => 'results'
+      redirect_to :controller => 'geocoder', :action => 'results', :params => @res_ary
     end
   end
 
   def result
     end
   end
 
   def result
-
+    @res = :params[@res_ary]
   end
 end
   end
 end