1 class GeocoderController < ApplicationController
5 require 'rexml/document'
12 if params[:query][:postcode]
13 postcode = params[:query][:postcode]
14 escaped_postcode = postcode.sub(/\s/,'%20')
16 if postcode.match(/(^\d{5}$)|(^\d{5}-\d{4}$)/)
17 # Its a zip code - ask geocoder.us
18 # (They have a non commerical use api)
19 Net::HTTP.start('rpc.geocoder.us') do |http|
20 resp = http.get("/service/csv?zip=#{postcode}")
21 data = resp.body.split(/, /) # lat,long,town,state,zip
24 redirect_to "/index.html?lat=#{lat}&lon=#{lon}&zoom=14"
26 elsif postcode.match(/^(\w{1,2}\d+\w?\s*\d\w\w)/)
27 # It matched our naive UK postcode regexp
28 # Ask npemap to do a combined npemap + freethepostcode search
29 Net::HTTP.start('www.npemap.org.uk') do |http|
30 resp = http.get("/cgi/geocoder.fcgi?format=text&postcode=#{escaped_postcode}")
31 dataline = resp.body.split(/\n/)[1]
32 data = dataline.split(/,/) # easting,northing,postcode,lat,long
35 redirect_to "/index.html?lat=#{lat}&lon=#{lon}&zoom=14"
38 # Some other postcode / zip file
39 redirect_to "/index.html?error=unknown_postcode_or_zip"
42 if params[:query][:place_name] != nil or ""
43 place_name = params[:query][:place_name]
44 Net::HTTP.start('ws.geonames.org') do |http|
45 res = http.get("/search?q=#{place_name}&maxRows=10")
46 xml = REXML::Document.new(res.body)
47 xml.elements.each("geonames/geoname") do |ele|
49 ele.elements.each("name"){ |n| res_hash['name'] = n.text }
50 ele.elements.each("countryCode"){ |n| res_hash['country_code'] = n.text }
51 ele.elements.each("countryNode"){ |n| res_hash['country_name'] = n.text }
52 ele.elements.each("lat"){ |n| res_hash['lat'] = n.text }
53 ele.elements.each("lng"){ |n| res_hash['lon']= n.text }
58 redirect_to :controller => 'geocoder', :action => 'results', :params => @res_ary
63 @res = :params[@res_ary]