Follow

Welcome to TechYari!

Tutorials on webdesign, web development and more...

Creating An Awesome LiveWeather App Using jQuery, Open Weather MAP API and BigVideo.js



By  Vipin Dubey     4/21/2014    Labels:,,,,,, 

Introduction

In this tutorial I am going to show you how to create an awesome Live Weather App using jQuery, jQuery UI autocomplete, Open Weather Map API and BigVideo.js.

OpenWeatherMap has a free API which provides weather details for almost every city around the world. I don't say that it's accurate but it's quite good to achieve what we need.

This application is compatible only with modern desktop browsers (built with Google Chrome not tested on others) as we are going to have an html5 video background and currently mobile devices do not support auto play for videos. There is a solution for this but we will park it for now.

live-weather-app-in-j2ee-using-jquery-json

weather-app-evening-background

weather-app-night-background

Requirements:

Open Weather Map API 

OpenWeatherMap provides a free api which can be called from below url (I have not used appid here, but it works without that as well):

URL : http://api.openweathermap.org/data/2.5/find?q=cityname&mode=json

here we are passing two parameters, city name & the response format we need from the server i.e. json in our case. You can use xml as well.
Below is a sample result for query using Mumbai as a city name :

{"message":"accurate","cod":"200","count":1,"list":[{"id":1275339,"name":"Mumbai","coord":{"lon":72.847939,"lat":19.01441},"main":{"temp":302.47,"temp_min":302.47,"temp_max":302.47,"pressure":1018.69,"sea_level":1019.47,"grnd_level":1018.69,"humidity":86},"dt":1398078846,"wind":{"speed":4.01,"deg":301.501},"sys":{"country":"IN"},"clouds":{"all":0},"weather":[{"id":800,"main":"Clear","description":"Sky is Clear","icon":"01d"}]}]}


Step 1 : Creating the Layout 

To create our layout we will us html5 based bootstrap template from http://www.initializr.com/ . Place all the videos, js and css files in required folders according to the index.html file code below, you can also download the source and see the structure of files and folders.


<!DOCTYPE html>
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="stylesheet" href="css/bootstrap.min.css">
        <link rel="stylesheet" href="css/bootstrap-theme.min.css">
        <link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/smoothness/jquery-ui.css" />
        <link rel="stylesheet" href="css/main.css">

        <script src="js/vendor/modernizr-2.6.2-respond-1.1.0.min.js"></script>
    </head>
    <body>
        <!--[if lt IE 7]>
            <p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
        <![endif]-->
        

        <div class="result">
                <div class="search">
                <input class="city_names" id="city_names" name="city_names" placeholder="Enter city name here"/>
                <input type = "button" name="submit" value="Search" id="submit" class="submit"/>
                </div>
                <div class="main">
                    <span class="city"></span>
                    <span class="country"></span>
                    <div class="temp"></div>
                    <div class="message"></div>
                </div>
          </div>

      
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
        <script>window.jQuery || document.write('<script src="js/vendor/jquery-1.11.0.min.js"><\/script>')</script>
        <script src="js/vendor/jquery-ui.min.js"></script>

        <script src="js/vendor/bootstrap.min.js"></script>
        <script src="js/vendor/imagesloaded.pkgd.min.js"></script>
        <script src="js/vendor/video.js"></script>
        <script src="js/vendor/bigvideo.js"></script>
        <script src="js/main.js"></script>

    
    </body>
</html>


Step 2 : Styling the page with css

So we have our layout ready with an input tag to get the city name and few empty html elements to render the data provided by api call. All of this is going to be done dynamically using jquery. But before moving to that lets style our page a bit, below is the code for main.css


.result{
  position:fixed;
  z-index: 100;  
  top:50%;  
  left:50%;  
  margin:-100px 0 0 -100px;  
  width:360px;  
  height:460px; 
}
.submit{color:black;}
.search{text-align: center;}
.main{text-align: center;color: white; }
.city{font-family: fantasy;
font-size: 76px;}
.country{font-family: fantasy;}
.temp, .t{font-weight: 700;
font-size: 72px;}
.temp-high{font-weight: bold;}
.temp-low{font-weight: bold;}


Step 3 : Configure the autocomplete for city names

You might have noticed that we have an input field on index page but it does not have any form, as we are going to use jQuery to submit the data to the sever on click event of submit button. Before doing that we need to configure one more thing i.e. "Autocomplete". We would like to show our users all the available cities as a dropdown list when they type on input. We will also show them the country code with the city to make it more convenient for them. to achieve this we will use the same api from openweathermap and just return the matching city names as label from the success of ajax call. below is the code for autocomplete..


$(document).ready(function(){
 $( ".city_names" ).autocomplete({
  source: function( request, response ) {
   $.ajax({
    url: "http://api.openweathermap.org/data/2.5/find",
    dataType: "jsonp",
    data: {
     q: request.term,
     mode: "json"
    },
    success: function( data ) {
     // Fix for IE 8 as forEach function not supported yet below IE 9
     if (typeof Array.prototype.forEach != 'function') {
         Array.prototype.forEach = function(callback){
           for (var i = 0; i < this.length; i++){
             callback.apply(this, [this[i], i, this]);
           }
         };
     }

     var parsed = data.list;
     var newArray = new Array(parsed.length);
     var i = 0;
       parsed.forEach(function (entry) {
                     var newObject = {
                         label: entry.name+" "+entry.sys.country
                     };
                     newArray[i] = newObject;
                     i++;
                 });

       response(newArray);
    },
    error: function (message) {
                 response([]);
             }
   });
  },
  minLength: 2,
  open: function() {
   $( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
  },
  close: function() {
   $( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
  }
 });
 
});


Step 4 : Geting the weather data from OpenWeatherMap API

To get weather data via api call we need to pass either city name, latitude,longitude or city id. This is not a practical scenario and just a demo so to keep things simpler our we will pass city name (This can have issues in terms of usability when their are multiple cities with the same name for a given country). 

OpenWeatherMap API provides all type of data for a location, we are only interested in current temperature in celcius format. Below is the code for submit button click event


$('.submit').click(function(){
 
 var city = $('.city_names').val();
 //console.log(city);
 $.ajax({
     url: "http://api.openweathermap.org/data/2.5/find",
  
     // name of the callback parameter
     jsonp: "callback",
  
     // tell jQuery we're expecting JSONP
     dataType: "jsonp",
  
     //what we want
     data: {
         q: city,
         units:"metric",
         mode: "json"
     },
  
     // work with the response
     success: function( response ) { 
        
      
             var temp = response.list[0].main.temp;
             
             if(temp<25 ){
              $('.message').html("it's feels cold, get a jacket");
             }else if(temp<35){
              $('.message').html("it's feels normal"); 
             }else if(temp<50){
              $('.message').html("it's feels hot, switch on your AC");
             }

        $('.city').html(response.list[0].name);
        $('.country').html('( </span><span>'+response.list[0].sys.country+'</span><span> )');
        $('.temp').html('<span>'+response.list[0].main.temp+'</span><span class="t">* C</span>');
       
         
     }
 });
});



 Step 5 : Adding the video background based on time of user's machine.  

We have used BigVideo.js to show video background, We have three videos, one for morning to afternoon, one for evening, and one for night. We will show them based on user's machine time (time on his laptop/deskto/device). Below is the code...


  var date = new Date();
    var hour = date.getHours();
             var min = date.getMinutes();

             //console.log("hour: "+hour+" minute: "+min);

             if(hour<5){
                   $(function() {
          var BV = new $.BigVideo();
          BV.init();
          BV.show(['night.mp4'],{ambient:true});
                   });
               }else if(hour<16){
                 $(function() {
          var BV = new $.BigVideo();
          BV.init();
          BV.show(['daylight.mp4'],{ambient:true});
                   });
               }else if(hour<19){
                 $(function() {
          var BV = new $.BigVideo();
          BV.init();
          BV.show(['evening.mp4'],{ambient:true});
                   });
               }else{
                    $(function() {
          var BV = new $.BigVideo();
          BV.init();
          BV.show(['night.mp4'],{ambient:true});
                   });
 }

Step 6 : combining all the three parts into a single javascript file


var date = new Date();
    var hour = date.getHours();
             var min = date.getMinutes();

             //console.log("hour: "+hour+" minute: "+min);

             if(hour<5){
                   $(function() {
          var BV = new $.BigVideo();
          BV.init();
          BV.show(['night.mp4'],{ambient:true});
                   });
               }else if(hour<16){
                 $(function() {
          var BV = new $.BigVideo();
          BV.init();
          BV.show(['daylight.mp4'],{ambient:true});
                   });
               }else if(hour<19){
                 $(function() {
          var BV = new $.BigVideo();
          BV.init();
          BV.show(['evening.mp4'],{ambient:true});
                   });
               }else{
                    $(function() {
          var BV = new $.BigVideo();
          BV.init();
          BV.show(['night.mp4'],{ambient:true});
                   });
 }

$('.submit').click(function(){
 
 var city = $('.city_names').val();
 //console.log(city);
 $.ajax({
     url: "http://api.openweathermap.org/data/2.5/find",
  
     // name of the callback parameter
     jsonp: "callback",
  
     // tell jQuery we're expecting JSONP
     dataType: "jsonp",
  
     //what we want
     data: {
         q: city,
         units:"metric",
         mode: "json"
     },
  
     // work with the response
     success: function( response ) { 
        
      
             var temp = response.list[0].main.temp;
             
             if(temp<25 ){
              $('.message').html("it's feels cold, get a jacket");
             }else if(temp<35){
              $('.message').html("it's feels normal"); 
             }else if(temp<50){
              $('.message').html("it's feels hot, switch on your AC");
             }

        $('.city').html(response.list[0].name);
        $('.country').html('( </span><span>'+response.list[0].sys.country+'</span><span> )');
        $('.temp').html('<span>'+response.list[0].main.temp+'</span><span class="t">* C</span>');
       
         
     }
 });
});

$(document).ready(function(){
 $( ".city_names" ).autocomplete({
  source: function( request, response ) {
   $.ajax({
    url: "http://api.openweathermap.org/data/2.5/find",
    dataType: "jsonp",
    data: {
     q: request.term,
     mode: "json"
    },
    success: function( data ) {
     // Fix for IE 8 as forEach function not supported yet below IE 9
     if (typeof Array.prototype.forEach != 'function') {
         Array.prototype.forEach = function(callback){
           for (var i = 0; i < this.length; i++){
             callback.apply(this, [this[i], i, this]);
           }
         };
     }

     var parsed = data.list;
     var newArray = new Array(parsed.length);
     var i = 0;
       parsed.forEach(function (entry) {
                     var newObject = {
                         label: entry.name+" "+entry.sys.country
                     };
                     newArray[i] = newObject;
                     i++;
                 });

       response(newArray);
    },
    error: function (message) {
                 response([]);
             }
   });
  },
  minLength: 2,
  open: function() {
   $( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
  },
  close: function() {
   $( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
  }
 });
 
});


That's all, you might get  5 second glitch on video background, which can be tweaked but I will leave it for now, we have successfully created a weather app using only html,css and jQuery. If you want to support mobile devices, you can include a check for mobile devices using main.js javascript file and replace video with a static background using css.

Share this tutorial if you find it useful and do comment if any questions/suggestions.

Download Source 



About Vipin Dubey

A web developer, blogger, amateur designer and an open source enthusiast.

No comments:

Post a Comment


Contact Form

Name

Email *

Message *

Labels

Follow TechYari on

Translate

About TechYari

Tech Yari is a Technical Blog featuring articles on Web Development, Web Design, Search Engine Optimization, Social Media Marketting and Programming.