Skip to content

Instantly share code, notes, and snippets.

@VerizonMediaOwner
Last active May 21, 2020 12:15
Show Gist options
  • Save VerizonMediaOwner/ec22d1568bd136a7e818371cd64ae2f5 to your computer and use it in GitHub Desktop.
Save VerizonMediaOwner/ec22d1568bd136a7e818371cd64ae2f5 to your computer and use it in GitHub Desktop.
Yahoo Weather API JavaScript Example
// Weather API sample javascript code
// Requires: jQuery and crypto-js (v3.1.9)
//
// Copyright 2019 Oath Inc. Licensed under the terms of the zLib license see https://opensource.org/licenses/Zlib for terms.
var url = 'https://weather-ydn-yql.media.yahoo.com/forecastrss';
var method = 'GET';
var app_id = 'your-app-id';
var consumer_key = 'your-consumer-key';
var consumer_secret = 'your-consumer-secret';
var concat = '&';
var query = {'location': 'sunnyvale,ca', 'format': 'json'};
var oauth = {
'oauth_consumer_key': consumer_key,
'oauth_nonce': Math.random().toString(36).substring(2),
'oauth_signature_method': 'HMAC-SHA1',
'oauth_timestamp': parseInt(new Date().getTime() / 1000).toString(),
'oauth_version': '1.0'
};
var merged = {};
$.extend(merged, query, oauth);
// Note the sorting here is required
var merged_arr = Object.keys(merged).sort().map(function(k) {
return [k + '=' + encodeURIComponent(merged[k])];
});
var signature_base_str = method
+ concat + encodeURIComponent(url)
+ concat + encodeURIComponent(merged_arr.join(concat));
var composite_key = encodeURIComponent(consumer_secret) + concat;
var hash = CryptoJS.HmacSHA1(signature_base_str, composite_key);
var signature = hash.toString(CryptoJS.enc.Base64);
oauth['oauth_signature'] = signature;
var auth_header = 'OAuth ' + Object.keys(oauth).map(function(k) {
return [k + '="' + oauth[k] + '"'];
}).join(',');
$.ajax({
url: url + '?' + $.param(query),
headers: {
'Authorization': auth_header,
'X-Yahoo-App-Id': app_id
},
method: 'GET',
success: function(data){
console.log(data);
}
});
@jcorbett123
Copy link

jcorbett123 commented Mar 20, 2019

I used to use yahoo weather api for my home, but I am not a programmer and wouldn't know where to begin to update the javascript and html to make it work again. Can you PLEASE help me! My daughters absolutely love looking up the weather!

Here is the jquery.simpleWeather5.js

/*! simpleWeather v3.1.0 - http://simpleweatherjs.com */
(function($) {
  'use strict';

  function getAltTemp(unit, temp) {
    if(unit === 'f') {
      return Math.round((5.0/9.0)*(temp-32.0));
    } else {
      return Math.round((9.0/5.0)*temp+32.0);
    }
  }

  $.extend({
    simpleWeather: function(options){
      options = $.extend({
        location: '',
        woeid: '',
        unit: 'f',
        success: function(weather){},
        error: function(message){}
      }, options);

      var now = new Date();
      var weatherUrl = 'https://query.yahooapis.com/v1/public/yql?format=json&rnd=' + now.getFullYear() + now.getMonth() + now.getDay() + now.getHours() + '&diagnostics=true&callback=?&q=';

      if(options.location !== '') {
        /* If latitude/longitude coordinates, need to format a little different. */
        var location = '';
        if(/^(\-?\d+(\.\d+)?),\s*(\-?\d+(\.\d+)?)$/.test(options.location)) {
          location = '(' + options.location + ')';
        } else {
          location = options.location;
        }

        weatherUrl += 'select * from weather.forecast where woeid in (select woeid from geo.places(1) where text="' + location + '") and u="' + options.unit + '"';
      } else if(options.woeid !== '') {
        weatherUrl += 'select * from weather.forecast where woeid=' + options.woeid + ' and u="' + options.unit + '"';
      } else {
        options.error('Could not retrieve weather due to an invalid location.');
        return false;
      }

      $.getJSON(
        encodeURI(weatherUrl),
        function(data) {
          if(data !== null && data.query !== null && data.query.results !== null && data.query.results.channel.description !== 'Yahoo! Weather Error') {
            var result = data.query.results.channel,
                weather = {},
                forecast,
                compass = ['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW', 'N'],
                image404 = 'https://s.yimg.com/os/mit/media/m/weather/images/icons/l/44d-100567.png';

            weather.title = result.item.title;
            weather.temp = result.item.condition.temp;
            weather.code = result.item.condition.code;
            weather.todayCode = result.item.forecast[0].code;
            weather.currently = result.item.condition.text;
            weather.high = result.item.forecast[0].high;
            weather.low = result.item.forecast[0].low;
            weather.text = result.item.forecast[0].text;
            weather.humidity = result.atmosphere.humidity;
            weather.pressure = result.atmosphere.pressure;
            weather.rising = result.atmosphere.rising;
            weather.visibility = result.atmosphere.visibility;
            weather.sunrise = result.astronomy.sunrise;
            weather.sunset = result.astronomy.sunset;
            weather.description = result.item.description;
            weather.city = result.location.city;
            weather.country = result.location.country;
            weather.region = result.location.region;
            weather.updated = result.item.pubDate;
            weather.link = result.item.link;
            weather.units = {temp: result.units.temperature, distance: result.units.distance, pressure: result.units.pressure, speed: result.units.speed};
            weather.wind = {chill: result.wind.chill, direction: compass[Math.round(result.wind.direction / 22.5)], speed: result.wind.speed};

            if(result.item.condition.temp < 80 && result.atmosphere.humidity < 40) {
              weather.heatindex = -42.379+2.04901523*result.item.condition.temp+10.14333127*result.atmosphere.humidity-0.22475541*result.item.condition.temp*result.atmosphere.humidity-6.83783*(Math.pow(10, -3))*(Math.pow(result.item.condition.temp, 2))-5.481717*(Math.pow(10, -2))*(Math.pow(result.atmosphere.humidity, 2))+1.22874*(Math.pow(10, -3))*(Math.pow(result.item.condition.temp, 2))*result.atmosphere.humidity+8.5282*(Math.pow(10, -4))*result.item.condition.temp*(Math.pow(result.atmosphere.humidity, 2))-1.99*(Math.pow(10, -6))*(Math.pow(result.item.condition.temp, 2))*(Math.pow(result.atmosphere.humidity,2));
            } else {
              weather.heatindex = result.item.condition.temp;
            }

            if(result.item.condition.code == '3200') {
              weather.thumbnail = image404;
              weather.image = image404;
            } else {
              weather.thumbnail = 'https://s.yimg.com/zz/combo?a/i/us/nws/weather/gr/' + result.item.condition.code + 'ds.png';
              weather.image = 'https://s.yimg.com/zz/combo?a/i/us/nws/weather/gr/' + result.item.condition.code + 'd.png';
            }

            weather.alt = {temp: getAltTemp(options.unit, result.item.condition.temp), high: getAltTemp(options.unit, result.item.forecast[0].high), low: getAltTemp(options.unit, result.item.forecast[0].low)};
            if(options.unit === 'f') {
              weather.alt.unit = 'c';
            } else {
              weather.alt.unit = 'f';
            }

            weather.forecast = [];
            for(var i=0;i<result.item.forecast.length;i++) {
              forecast = result.item.forecast[i];
              forecast.alt = {high: getAltTemp(options.unit, result.item.forecast[i].high), low: getAltTemp(options.unit, result.item.forecast[i].low)};

              if(result.item.forecast[i].code == "3200") {
                forecast.thumbnail = image404;
                forecast.image = image404;
              } else {
                forecast.thumbnail = 'https://s.yimg.com/zz/combo?a/i/us/nws/weather/gr/' + result.item.forecast[i].code + 'ds.png';
                forecast.image = 'https://s.yimg.com/zz/combo?a/i/us/nws/weather/gr/' + result.item.forecast[i].code + 'd.png';
              }

              weather.forecast.push(forecast);
            }

            options.success(weather);
          } else {
            options.error('There was a problem retrieving the latest weather information.');
          }
        }
      );
      return this;
    }
  });
})(jQuery);

And here is the html

<!DOCTYPE html> 
<html lang="en"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>5 Day Forecast</title>
<style>
html, body {
	height: 100%;
	margin: 0;
	overflow:hidden;
}
h1 {
    margin: 2.15vh;
    padding: 0;
    border: 0;
}
h2 {
    margin: 2vh;
    padding: 0;
    border: 0;
}
h3 {
    margin: 0;
    padding: 0;
    border: 0;
}
img {
    padding: 0;
    margin: 1vh 0vh;
    display: block;
}
#container {
	width:100%;
	height:100%;
}
#zero {
	width:20%;
	height:100%;
	float:left;
	background: linear-gradient(to bottom, #FFFFFF 0%, #C0CFE2 100%);
}
#one {
	width:20%;
	height:100%;
	float:left;
	background: linear-gradient(to bottom, #C0CFE2 0%, #FFFFFF 100%);
}
#two {
	width:20%;
	height:100%;
	float:left;
	background: linear-gradient(to bottom, #FFFFFF 0%, #C0CFE2 100%);
}
#three {
	width:20%;
	height:100%;
	float:left;
	background: linear-gradient(to bottom, #C0CFE2 0%, #FFFFFF 100%);
}
#four {
	width:20%;
	height:100%;
	float:left;
	background: linear-gradient(to bottom, #FFFFFF 0%, #C0CFE2 100%);
}
</style>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="jquery.simpleWeather5.js" charset="utf-8"></script>
	<script type="text/javascript">
		$(function() {
			$.simpleWeather({
				location: '68164',
				unit: 'f',
				success: function(weather0) {
					html = '<h1>'+weather0.forecast[0].day+'</h1>';
					html += '<h2>'+weather0.forecast[0].date+'</h2>';
					html += '<img src="wthr/'+weather0.forecast[0].code+'.png" width="100%">';
					html += '<h2>High: '+weather0.forecast[0].high+'</h2>';
					html += '<h2>Low: '+weather0.forecast[0].low+'</h2>';
					html += '<h2>'+weather0.forecast[0].text+'</h2>';
					
					$("#weather0").html(html);
				},
				error: function(error) {
					$("#weather0").html('<p>'+error+'</p>');
				}
			});			
		});
	</script>
	<script type="text/javascript">
		$(function() {
			$.simpleWeather({
				location: '68164',
				unit: 'f',
				success: function(weather1) {
					html = '<h1>'+weather1.forecast[1].day+'</h1>';
					html += '<h2>'+weather1.forecast[1].date+'</h2>';
					html += '<img src="wthr/'+weather1.forecast[1].code+'.png" width="100%">';
					html += '<h2>High: '+weather1.forecast[1].high+'</h2>';
					html += '<h2>Low: '+weather1.forecast[1].low+'</h2>';
					html += '<h2>'+weather1.forecast[1].text+'</h2>';
					
					$("#weather1").html(html);
				},
				error: function(error) {
					$("#weather1").html('<p>'+error+'</p>');
				}
			});
		});
	</script>
	<script type="text/javascript">
		$(function() {
			$.simpleWeather({
				location: '68164',
				unit: 'f',
				success: function(weather2) {
					html = '<h1>'+weather2.forecast[2].day+'</h1>';
					html += '<h2>'+weather2.forecast[2].date+'</h2>';
					html += '<img src="wthr/'+weather2.forecast[2].code+'.png" width="100%">';
					html += '<h2>High: '+weather2.forecast[2].high+'</h2>';
					html += '<h2>Low: '+weather2.forecast[2].low+'</h2>';
					html += '<h2>'+weather2.forecast[2].text+'</h2>';
					
					$("#weather2").html(html);
				},
				error: function(error) {
					$("#weather2").html('<p>'+error+'</p>');
				}
			});			
		});
	</script>
	<script type="text/javascript">
		$(function() {
			$.simpleWeather({
				location: '68164',
				unit: 'f',
				success: function(weather3) {
					html = '<h1>'+weather3.forecast[3].day+'</h1>';
					html += '<h2>'+weather3.forecast[3].date+'</h2>';
					html += '<img src="wthr/'+weather3.forecast[3].code+'.png" width="100%">';
					html += '<h2>High: '+weather3.forecast[3].high+'</h2>';
					html += '<h2>Low: '+weather3.forecast[3].low+'</h2>';
					html += '<h2>'+weather3.forecast[3].text+'</h2>';
					
					$("#weather3").html(html);
				},
				error: function(error) {
					$("#weather3").html('<p>'+error+'</p>');
				}
			});			
		});
	</script>
	<script type="text/javascript">
		$(function() {
			$.simpleWeather({
				location: '68164',
				unit: 'f',
				success: function(weather4) {
					html = '<h1>'+weather4.forecast[4].day+'</h1>';
					html += '<h2>'+weather4.forecast[4].date+'</h2>';
					html += '<img src="wthr/'+weather4.forecast[4].code+'.png" width="100%">';
					html += '<h2>High: '+weather4.forecast[4].high+'</h2>';
					html += '<h2>Low: '+weather4.forecast[4].low+'</h2>';
					html += '<h2>'+weather4.forecast[4].text+'</h2>';
					
					$("#weather4").html(html);
				},
				error: function(error) {
					$("#weather4").html('<p>'+error+'</p>');
				}
			});			
		});
	</script>
</head>
<body bgcolor="ffffff">
<center><h1>5-DAY FORECAST</h1></center>
<div id="container">
    <div id="zero"><center><div id="weather0"></div></center></div>
    <div id="one"><center><div id="weather1"></div></center></div>
    <div id="two"><center><div id="weather2"></div></center></div>
    <div id="three"><center><div id="weather3"></div></center></div>
    <div id="four"><center><div id="weather4"></div></center></div>
</div>
</body>
</html>

@craigtommola
Copy link

I used to use yahoo weather api for my home, but I am not a programmer and wouldn't know where to begin to update the javascript and html to make it work again. Can you PLEASE help me! My daughters absolutely love looking up the weather!

Here is the jquery.simpleWeather5.js

Simple Weather no longer works and is not being updated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment