Weather Forecast App

In this example below you will see how to do a Weather Forecast App with some HTML / CSS and Javascript

Thumbnail
This awesome code was written by rxrossi, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright rxrossi ©
  • HTML
  • CSS
  • JavaScript
    <html>
  <head>
    <title>Weather Forecast App</title>
  </head>
  <body>
    <div class="container" id="data">
      <div id="error"></div>
      <!--
      <p id="latitude"></p>
      <p id="longitude"></p> 
      -->
      
      <div id="mainContainer" class="row text-center">
        <div class="col-sm-12">
          <h1>Weather conditions app</h1>
          <hr />
          <p><span id="city"></span>, <span id="region"></span> - <span id="country"></span></p>
          <p>
            <span id="date"></span>
          </p>
       </div>
       <div class="col-sm-6 blackBg"> 
         <h2>Current conditions:</h2>
         <p>      
           <span id="temp"></span> <span class="tempUnit"></span>
         </p> 
         <p>
           <span id="decriptionOfWeather"></span>
         </p>
       </div>
        
       <div class="col-sm-6 blackBg"> 
         <h2>Forecast for today:</h2>
         <p>      
           Min: <span id="minTempToday"></span> <span class="tempUnit"></span>, Max: <span id="maxTempToday"></span> <span class="tempUnit"></span> 
         </p> 
         <p>
           <span id="decriptionOfWeatherForecast"></span>
         </p>
       </div>  
        
      </div>
      
      <div id="btns" class="col-xs-12 text-center">
        <button id="changeUnit" class="btn btn-sm btn-info"></button>
      </div>
  
    </div> <!-- end of Container -->
    
    <div id="footer">
      <p>Information provided by Yahoo</p>
    </div>
  </body>
</html>

/*Downloaded from https://www.codeseek.co/rxrossi/weather-forecast-app-kkGwWj */
    body {
  background-repeat: no-repeat;
  background-position: center center;
  background-attachment: fixed;
  background-size: cover;
}

#mainContainer, #footer {
  margin-top: 10px;
  font-size: 150%;
  color: #eee;
  text-shadow: 2px 2px #000; 
  padding: 30px;
  position: relative;
}

#mainContainer h1 {
  color: #fff;
}

#footer {
  position: absolute;
  bottom: 0;
  font-size: 70%;
  padding: 10px 10px 0 0;
  text-align: right;
  width: 100%;
}

#btns {
  margin-top: 15px;
}

.blackBg {
  background: rgba(0, 0, 0, 0.5);
  padding: 20px;
}




/*Downloaded from https://www.codeseek.co/rxrossi/weather-forecast-app-kkGwWj */
    if ("geolocation" in navigator) {
  /* geolocation is available */
  //console.log("geolocation working");
  navigator.geolocation.getCurrentPosition(useLocation, handleLocationErrors);
} else {
  console.log("not working");
  /* geolocation IS NOT available */
}

var positionStr;
var unitStr = "f";

function useLocation (position) {
  //$("#latitude").html("Latitude: " + position.coords.latitude);
  //$("#longitude").html("Latitude: " +  position.coords.longitude);
  positionStr = position.coords.latitude+"%2C"+position.coords.longitude;
  getData(positionStr, unitStr);
}

function handleLocationErrors (err) {
  console.log(err);
  if (err.code === 1) {
    $("#error").html("<p>I'm sorry, I can't find your location, you could try in a different browser or device, here is what your browser tells me: " + err.message + " </p>")
  }
}

var weatherCodes = {
  0: ["tornado", "http://www.blirk.net/wallpapers/1920x1080/road-wallpaper-5.jpg"],
  1: ["tropical storm", "http://belizeadventure.com/wp-content/uploads/2013/04/northern-storm-2003.jpg"],
  2: ["hurricane", "http://wallup.net/wp-content/uploads/2016/01/87942-Desktopography-Natural_Disaster-hurricane-water-digital_art-tornado.jpg"],
  3: ["severe thunderstorms", "https://3.bp.blogspot.com/-DmhCqatx-h0/UEdIPnSKxzI/AAAAAAAAUmk/IRLkvwC7voI/s1600/Thunder.jpg"],
  4: ["thunderstorms", "https://c2.staticflickr.com/4/3731/14086155389_0c1ea61ff8_k.jpg"],
  5: ["mixed rain and snow", "https://c1.staticflickr.com/1/128/347166853_97a7876a49_o.jpg"],
  6: ["mixed rain and sleet", "https://c1.staticflickr.com/9/8367/8500464559_0237da92bf_k.jpg"],
  7: ["mixed snow and sleet", "https://c2.staticflickr.com/8/7550/16131472139_30ea121a9d_k.jpg"],
  8: ["freezing drizzle", "https://upload.wikimedia.org/wikipedia/commons/0/0c/Freezing_Rain_on_Tree_Branch.jpg"],
  9: ["drizzle", "https://cashmerewalks.files.wordpress.com/2011/03/img00305.jpg"],
  10: ["freezing rain", "http://www.trbimg.com/img-52cf823b/turbine/bal-winter-fire-hydrant-p2-20140109/2048/2048x1990"],
  11: ["showers", "http://www.trbimg.com/img-573fed7c/turbine/cgnews-heavy-rain-saturday-showers-sunday-and-monday-20160520"],
  12: ["showers", "http://www.trbimg.com/img-573fed7c/turbine/cgnews-heavy-rain-saturday-showers-sunday-and-monday-20160520"],
  13: ["snow flurries", "https://c2.staticflickr.com/8/7166/6639111279_702f9c0d7c_o.jpg"],
  14: ["light snow showers", "https://4.bp.blogspot.com/-zLMEz34-JvQ/VNctKRpPo4I/AAAAAAAADCI/fxRLrr51Sfo/s1600/2015-02-07%2B10.45.51-2.jpg"],
  15: ["blowing snow", "https://i.ytimg.com/vi/OhqIILyct5A/maxresdefault.jpg"],
  16: ["snow", "https://static.pexels.com/photos/4022/cold-snow-forest-trees.jpeg"],
  17: ["hail", "https://i.ytimg.com/vi/utPa2F34_Kw/maxresdefault.jpg"],
  18: ["sleet", "https://i.ytimg.com/vi/AhBFanbd6Ng/maxresdefault.jpg"],
  19: ["dust", "https://resources0.news.com.au/images/2009/09/23/1225778/487336-sydney-039-s-red-dust-storm.jpg"],
  20: ["foggy", "https://a2ua.com/foggy/foggy-001.jpg"],
  21: ["haze", "https://a2ua.com/haze/haze-010.jpg"],
  22: ["smoky", "http://cdn.history.com/sites/2/2013/11/tennessee-smokey-mountains.jpg"],
  23: ["blustery", "http://randomwallpapers.net/windy-winter-1920x1200-wallpaper430287.jpg"],
  24: ["windy", "http://digitalphotographysecrets.com/wp-content/uploads/2012/02/591139_19425673.jpg"],
  25: ["cold", "http://i.huffpost.com/gen/2332996/images/o-VERY-COLD-facebook.jpg"],
  26: ["cloudy", "https://wallpaperscraft.com/image/dock_boat_cloudy_81320_1920x1080.jpg"],
  27: ["mostly cloudy (night)", "http://cdn.weatheravenue.com/img/background/background-night.jpg"],
  28: ["mostly cloudy (day)" , "https://tau0.files.wordpress.com/2012/08/south_tx_cloudy_sky.jpg"],
  29: ["partly cloudy (night)", "https://wildernessvagabonds.com/blog/wp-content/uploads/2013/01/partly_cloudy.jpg"],
  30: ["partly cloudy (day)", "http://www.weather.polischrysochous.net/images/day/partlycloudy.jpg"],
  31: ["clear (night)", "https://snapshotsbykats.files.wordpress.com/2011/11/020.jpg"],
  32: ["sunny", "http://www.mrwallpaper.com/wallpapers/sunny-day-landscape.jpg"],
  33: ["fair (night)", "http://www.photoshelter.com/img-get/I000059belCzVk48/s/590/393/IDSW2013mountVictoria.jpg"],
  34: ["fair (day)", "http://www.youwall.com/wallpapers/201207/sunny-day-wallpaper-1440x900.jpg"],
  35: ["mixed rain and hail", "https://i.ytimg.com/vi/SLGNBiRk6gQ/maxresdefault.jpg"],
  36: ["hot", "http://better-biking.com/wp-content/uploads/2013/07/Hot_weather1Modv2.jpg"],
  37: ["isolated thunderstorms", "https://s-media-cache-ak0.pinimg.com/originals/a5/33/32/a53332acaa6aa60a0f0336cc1f327521.jpg"],
  38: ["scattered thunderstorms", "http://www.trbimg.com/img-55a053ca/turbine/dp-scattered-thunderstorms-in-saturdays-forecast-20150710"],
  39: ["scattered thunderstorms", "http://www.trbimg.com/img-55a053ca/turbine/dp-scattered-thunderstorms-in-saturdays-forecast-20150710"],
  40: ["scattered showers", "http://www.nelive.in/sites/default/files/09-06-15%20Demow-%20Students%20returning%20home%20during%20rain%20(4).jpg"],
  41: ["heavy snow", "http://72ppi.us/photoblog/cache/c4/98/c4983caef3abf39c3c4f7c579a137b3e.jpg"],
  42: ["scattered snow showers", "https://tribwxin.files.wordpress.com/2013/02/thorton-in-snow.jpg?quality=85&strip=all"],
  43: ["heavy snow", "http://72ppi.us/photoblog/cache/c4/98/c4983caef3abf39c3c4f7c579a137b3e.jpg"],
  44: ["partly cloudy", "http://www.westessexnow.com/uploads/3/0/7/7/30776419/839755_orig.jpg"],
  45: ["thundershowers", "http://www.team-bhp.com/forum/attachments/shifting-gears/915665-official-non-auto-image-thread-dsc_5099.jpg"],
  46: ["snow showers", "https://lintvwood.files.wordpress.com/2013/10/snow-fennville.jpg"],
  47: ["isolated thundershowers", "https://s-media-cache-ak0.pinimg.com/originals/a5/33/32/a53332acaa6aa60a0f0336cc1f327521.jpg"],
  3200: ["not available", ""]

}

function getData (position, units) {
  $.getJSON("https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(SELECT%20woeid%20FROM%20geo.places%20WHERE%20text%3D%22("+position+")%22)%20and%20u=%27"+ units +"%27%0A&format=json&diagnostics=true&callback=?").done(function(data){
    
    // console.log(data.query.results.channel)
    
    //location
    $("#city").html(data.query.results.channel.location.city);
    $("#region").html(data.query.results.channel.location.region);
    $("#country").html(data.query.results.channel.location.country);
    
    //Current
    $("#temp").html(data.query.results.channel.item.condition.temp + " º");
    $(".tempUnit").html(data.query.results.channel.units.temperature);
    
    //Forecast today
    $("#decriptionOfWeatherForecast").html(data.query.results.channel.item.forecast[0].text);
    $("#minTempToday").html(data.query.results.channel.item.forecast[0].low + " º");
    $("#maxTempToday").html(data.query.results.channel.item.forecast[0].high + " º");
    
    if (unitStr === "f") {
      $("#changeUnit").html("to Celcius");
    } else {
      $("#changeUnit").html("to Fahrenheit");
    }
    
    $("#decriptionOfWeather").html(data.query.results.channel.item.condition.text);
    console.log("Code of weather: " + data.query.results.channel.item.condition.code);
    
    var date = new Date ( Date(data.query.results.channel.item.condition.date) );
    var options = {
        weekday: "long", year: "numeric", month: "short",
        day: "numeric", hour: "2-digit", minute: "2-digit"
    };    
    $("#date").html(date.toLocaleTimeString("en-us", options));
    
    $("#weatherCondition").html(data.query.results.channel.item.condition.text);
    $('body').css({backgroundImage : 'url(' + weatherCodes[data.query.results.channel.item.condition.code][1] + ')'});
    
  });
}

$("#changeUnit").on("click", function () {
  if (unitStr === "c") {
    unitStr = "f"
  } else {
    unitStr = "c"
  }
  getData(positionStr, unitStr);
 
});


Comments