]> git.openstreetmap.org Git - rails.git/blob - app/controllers/geocoder_controller.rb
bdddac3bbfa8b6ef73981e009925756ac753f324
[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       if postcode.match(/(^\d{5}$)|(^\d{5}-\d{4}$)/)
16         #its a zip code - do something
17       else
18         # Assume it's a UK postcode. 
19         # Fairly naive regexp is: \w{1,2}\d+\w?\s?\d\w\w
20        
21         # Ask npemap to do a combined npemap + freethepostcode search
22         Net::HTTP.start('www.npemap.org.uk') do |http|
23           resp = http.get("/cgi/geocoder.fcgi?format=text&postcode=#{escaped_postcode}")
24           dataline = resp.body.split(/\n/)[1]
25           data = dataline.split(/,/) # easting,northing,postcode,lat,long
26           lat = data[3] 
27           lon = data[4]
28           $stderr.print postcode
29           $stderr.print dataline
30           redirect_to "/index.html?lat=#{lat}&lon=#{lon}&zoom=14"
31         end
32       end
33     else
34       if params[:query][:place_name] != nil or "" 
35         place_name = params[:query][:place_name]
36         Net::HTTP.start('ws.geonames.org') do |http|
37           res = http.get("/search?q=#{place_name}&maxRows=10")
38           xml = REXML::Document.new(res.body)
39           xml.elements.each("geonames/geoname") do |ele|
40             res_hash = {}
41             ele.elements.each("name"){ |n| res_hash['name'] = n.text }
42             ele.elements.each("countryCode"){ |n| res_hash['country_code'] = n.text }
43             ele.elements.each("countryNode"){ |n| res_hash['country_name'] = n.text }
44             ele.elements.each("lat"){ |n| res_hash['lat'] = n.text }
45             ele.elements.each("lng"){ |n| res_hash['lon']= n.text }
46             @res_ary << res_hash
47           end 
48         end
49       end
50       redirect_to :controller => 'geocoder', :action => 'results', :params => @res_ary
51     end
52   end
53
54   def result
55     @res = :params[@res_ary]
56   end
57 end