- @res_hash = {}
- @postcode_arr = []
-
-
- if params[:query][:place_name] != nil or ""
- place_name = params[:query][:place_name]
- Net::HTTP.start('ws.geonames.org') do |http|
- res = http.get("/search?q=#{place_name}&maxRows=10")
- xml = REXML::Document.new(res.body)
- xml.elements.each("/geonames/geoname") do |ele|
- ele.elements.each("name"){ |n| @res_hash['name'] = n.text }
- ele.elements.each("countryCode"){ |n| @res_hash['country'] = n.text }
- ele.elements.each("lat"){ |n| @res_hash['lat'] = n.text }
- ele.elements.each("lng"){ |n| @res_hash['lon']= n.text }
- end
- end
+ @query = params[:query]
+ @results = Array.new
+
+ if @query.match(/^\d{5}(-\d{4})?$/)
+ @results.push search_us_postcode(@query)
+ elsif @query.match(/(GIR 0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKS-UW])\s*[0-9][ABD-HJLNP-UW-Z]{2})/i)
+ @results.push search_uk_postcode(@query)
+ elsif @query.match(/[A-Z]\d[A-Z]\s*\d[A-Z]\d/i)
+ @results.push search_ca_postcode(@query)
+ else
+ @results.push search_osm_namefinder(@query)
+ @results.push search_geonames(@query)
+ end
+ end
+
+private
+
+ def search_us_postcode(query)
+ results = Array.new
+
+ # ask geocoder.us (they have a non-commercial use api)
+ response = fetch_text("http://rpc.geocoder.us/service/csv?zip=#{URI.escape(query)}")
+
+ # parse the response
+ unless response.match(/couldn't find this zip/)
+ data = response.split(/\s*,\s+/) # lat,long,town,state,zip
+ results.push({:lat => data[0], :lon => data[1], :zoom => 12,
+ :prefix => "#{data[2]}, #{data[3]}, ",
+ :name => data[4]})
+ end
+
+ return { :source => "Geocoder.us", :url => "http://geocoder.us/", :results => results }
+ rescue Exception => ex
+ return { :source => "Geocoder.us", :url => "http://geocoder.us/", :error => "Error contacting rpc.geocoder.us: #{ex.to_s}" }
+ end
+
+ def search_uk_postcode(query)
+ results = Array.new
+
+ # ask npemap.org.uk to do a combined npemap + freethepostcode search
+ response = fetch_text("http://www.npemap.org.uk/cgi/geocoder.fcgi?format=text&postcode=#{URI.escape(query)}")
+
+ # parse the response
+ unless response.match(/Error/)
+ dataline = response.split(/\n/)[1]
+ data = dataline.split(/,/) # easting,northing,postcode,lat,long
+ results.push({:lat => data[3], :lon => data[4], :zoom => 12,
+ :name => data[2].gsub(/'/, "")})