updated geocoder
[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   before_filter :authorize_web
8   before_filter :require_user
9
10   def search
11     res_hash = {}
12     @postcode_arr = []
13     @res_ary = []
14
15     if params[:query][:postcode] != "" 
16       postcode = params[:query][:postcode]
17       if postcode.match(/(^\d{5}$)|(^\d{5}-\d{4}$)/)
18         #its a zip code - do something
19       else
20         Net::HTTP.start('www.freethepostcode.org') do |http|
21           resp = http.get("/geocode?postcode=#{postcode}")
22           lat = resp.body.scan(/[4-6][0-9]\.?[0-9]+/)
23           lon = resp.body.scan(/[-+][0-9]\.?[0-9]+/)
24           @postcode_array = [lat, lon]
25           redirect_to "/index.html?lat=#{@postcode_array[0]}&lon=#{@postcode_array[1]}&zoom=14"
26         end
27       end
28     else
29       if params[:query][:place_name] != nil or "" 
30         place_name = params[:query][:place_name]
31         Net::HTTP.start('ws.geonames.org') do |http|
32           res = http.get("/search?q=#{place_name}&maxRows=10")
33           xml = REXML::Document.new(res.body)
34           xml.elements.each("geonames/geoname") do |ele|
35             res_hash = {}
36             ele.elements.each("name"){ |n| res_hash['name'] = n.text }
37             ele.elements.each("countryCode"){ |n| res_hash['country_code'] = n.text }
38             ele.elements.each("countryNode"){ |n| res_hash['country_name'] = n.text }
39             ele.elements.each("lat"){ |n| res_hash['lat'] = n.text }
40             ele.elements.each("lng"){ |n| res_hash['lon']= n.text }
41             @res_ary << res_hash
42           end 
43         end
44       end
45       redirect_to :controller => 'geocoder', :action => 'results'
46     end
47   end
48
49   def result
50
51   end
52 end