updated the geocoder
[rails.git] / app / controllers / geocoder_controller.rb
1 class GeocoderController < ApplicationController
2
3   require 'net/http'
4   require 'rexml/document'
5
6   def search
7     @res_hash = {}
8     @postcode_arr = []
9
10
11     if params[:query][:place_name] != nil or "" 
12       place_name = params[:query][:place_name]
13       Net::HTTP.start('ws.geonames.org') do |http|
14         res = http.get("/search?q=#{place_name}&maxRows=10")
15         xml = REXML::Document.new(res.body)
16         xml.elements.each("/geonames/geoname") do |ele|
17           ele.elements.each("name"){ |n| @res_hash['name'] = n.text }
18           ele.elements.each("countryCode"){ |n| @res_hash['country'] = n.text }
19           ele.elements.each("lat"){ |n| @res_hash['lat'] = n.text }
20           ele.elements.each("lng"){ |n| @res_hash['lon']= n.text }
21         end
22       end
23     end
24     
25     if params[:query][:postcode]
26       postcode = params[:query][:postcode]
27       Net::HTTP.start('www.freethepostcode.org') do |http|
28         unless resp.code ~ /^2*/
29         resp = http.get("/geocode?postcode=#{postcode}")
30         lat = resp.body.scan(/[4-6][0-9]\.?[0-9]+/)
31         lon = resp.body.scan(/[-+][0-9]\.?[0-9]+/)
32         @postcode_array = [lat, lon]
33       else
34       end
35       redirect_to "/index.html?lat=#{@postcode_array[0]}&lon=#{@postcode_array[1]}&zoom=14"
36     end
37   end
38 end