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