Skip to content

Instantly share code, notes, and snippets.

@drewdeponte
Created December 12, 2010 01:22
Show Gist options
  • Save drewdeponte/737771 to your computer and use it in GitHub Desktop.
Save drewdeponte/737771 to your computer and use it in GitHub Desktop.
Get the Probability of Precipitation from Weather Service REST API
#!/usr/bin/env ruby
require 'rubygems'
require 'rest_client'
require 'rexml/document'
def getHourProbPrecip(zipcodes_array)
zipcodes_str = zipcodes_array.join('+')
results = {}
# Note: I set this time internal to this function and the way I do because
# the web service returns probability of precipiation in 12 hour increments
# 12 hours. Therefore it returns two values when the start and end date
# and times differ greater than 4 hours. Since, the code below only parses
# one value and assumes there is one value I am simplifying the function
# by not having the begin_time and end_time be parameters.
begin_time = Time.new().utc()
end_time = begin_time
# Define the start and end date and time to get the forcast for.
s_datetime = begin_time.strftime('%Y-%m-%dT%H:%M:%S')
e_datetime = end_time.strftime('%Y-%m-%dT%H:%M:%S')
puts s_datetime.inspect
puts e_datetime.inspect
# Build the propery request URL for the national weather services REST API.
weather_url = "http://www.weather.gov/forecasts/xml/sample_products/browser_interface/ndfdXMLclient.php?zipCodeList=#{zipcodes_str}&product=time-series&begin=#{s_datetime}&end=#{e_datetime}&pop12=pop12"
res = RestClient.get weather_url
puts res
doc, posts = REXML::Document.new(res), []
puts "Getting location keys"
i = 0
doc.elements.each('dwml/data/location') do |loc|
puts i.inspect
loc.elements.each('location-key') do |lk|
puts zipcodes_array[i].inspect
results[zipcodes_array[i]] = {}
results[zipcodes_array[i]].merge!({ :location_key => lk.text })
puts results[zipcodes_array[i]].inspect
end
i = i + 1
end
puts results.inspect
puts "Getting prob of precipitations"
z = 0
doc.elements.each('dwml/data/parameters/probability-of-precipitation/value') do |prob|
puts z.inspect
results[zipcodes_array[z]].merge!({ :prob_perc => prob.text })
puts results[zipcodes_array[z]].inspect
z = z + 1
end
puts results.inspect
return results
end
# Query the database via the locations table and group by postal to get a
# listing of lat lon pairs for each of the zip codes.
# zipcodes = '20910+25414'
zipcodes = ['92845', '90720']
foo = getHourProbPrecip(zipcodes)
foo.each { |k,v|
puts "ZipCode: #{k}"
puts "\tLocation Key: #{v[:location_key]}"
puts "\tProb Precipitation: #{v[:prob_perc]}"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment