Skip to main content

Create a local weather application using APIs


Today I am going to tell how to create a local weather application in Scratch using web APIs. We will use basic HTML and CSS to design the layout of our application. I am going to use JavaScript build the logic and some jQuery to add interactivity in the application. We will be using Google Maps API to get the current location and Drak Sky API to get the weather information in that location. You can follow with me with this tutorial and able to build this awesome weather application. So let's get started.

Step 1: Folder Structure 

Open up your favourite text editor and create a folder structure like bellow.

Local-Weather-App
 - css
   -- style.css
 - js
   -- script.js
 index.html


Step 2: Creating Basic HTML Layout

Add the following in index.html.

<!DOCTYPE html>
<html>
<title>W3.CSS Template</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<body>
<div >
    <div">
        <div   id="temp"><span id="iTemp"></span> °<span id="cUnit">C</span></div>
        <div   id="wIcon"><canvas id="icon1" width="128" height="128"></canvas></div>
        <div   id="summary"></div>
    </div>
    <div >
        <p><h4 id="date"></h4></p>
        <h4  id="caption"></h4>
        <div>
            <a   href="#" id="btn-unit">Change Units</a>
        </div>
    </div>
</div>
</body>
</html>


Step 3: Adding Styles

Now we have created the basic layout of our application. Now Let's few styles to our application. We will be using W3.CSS and Google Fonts. Add the following lines in head seaction of the index.html document.

<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway">

<link rel="stylesheet" href="css/style.css">

Now let's add the following styles to style.css file in CSS directory

body,h1,h5 {font-family: "Raleway", sans-serif}
body, html {height: 100%}
.bgimg {
  background: url("https://source.unsplash.com/0TND2_18n-s/1600x900") no-repeat center center fixed;
  min-height: 100%;
  background-position: center;
  background-size: cover;
}
.text-center{
  text-align: center;
}
.jumbotron {
  box-shadow: 0 8px 16px -6px #000807;
  background: rgba(0,0,0,0.4);


You can use any background image as you wish. I am going to use unsplash.com But you are free to use your own images. Now we have to add the CSS classes to our HTML document.

<div class="bgimg w3-display-container w3-text-white jumbotron">
    <div class="w3-display-middle w3-jumbo" >
        <div  class="text-center" id="temp"><span id="iTemp"></span> °<span id="cUnit">C</span></div>
        <div   class="text-center" id="wIcon"><canvas id="icon1" width="128" height="128"></canvas></div>
        <div   class="text-center" id="summary"></div>

    </div>

    <div  class="w3-display-bottomleft w3-container">
        <p><h4 id="date"></h4></p>
        <h4  id="caption"></h4>
        <div>
            <a   href="#" id="btn-unit">Change Units</a>
        </div>

    </div>

Step 4: Setting Weather API

We will be using Google Maps API

https://maps.googleapis.com/maps/api/geocode/json?sensor=true&latlng={latitude,longitude}

To use this API you need to pass latitude, longitude.For example, lets you 6.912586,79.850612 and test this API.

Paste this URL in your web browser. It will give a JSON result set displaying information about the location.
https://maps.googleapis.com/maps/api/geocode/json?sensor=true&latlng=6.912586,79.850612
Now let's get the weather API. For that, I am going to use Drak Sky API. Create a developers account and you will get URL of the API. For this, we need the latitude, longitude Get weather details.

Paste this URL into your web browser. It will give JSON result of weather information.
https://api.darksky.net/forecast/dc6bc895748dbac11e77e6fcc9ed29e5/3d7.8267,-122.4233

Step 5: Get Current Location and Weather

Let's add the First include the following script to the index.html document.

<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js'></script>
<script src='https://rawgithub.com/darkskyapp/skycons/master/skycons.js'></script>
<script src="js/script.js"></script>

Inside the script.js file type the following code.

$(document).ready(function() {

  // API-URLs
  var mapsURL = "https://maps.googleapis.com/maps/api/geocode/json?sensor=true&latlng=";
  var weatherURL = "https://api.darksky.net/forecast/dc6bc895748dbac11e77e6fcc9ed29e5/";

  var background = {
    "clear-day": "6gBJYHJim9o",
    "clear-night": "XcRpZxcIrNk",
    "partly-cloudy-day": "pmX9BkDDr_A",
    "partly-cloudy-night": "g3QBQto9Jt0",
    "cloudy": "FAA_bYB7VTg",
    "rain": "Nw_D8v79PM4",
    "sleet": "HOtPD7Z_74s",
    "snow": "zYJkisrhskE",
    "wind": "stLXUcN2Dac",
    "fog": "fRqmRtjfe64"
  };

  if ("geolocation" in navigator) {
  /* geolocation is available */
    // get current position
    navigator.geolocation.getCurrentPosition(function(position) {

      // store latitude and longitude
      var lat = position.coords.latitude;
      var long = position.coords.longitude;

      console.log(lat + ',' + long);

      // get current address using Google Maps API
      $.getJSON(mapsURL + lat + ',' + long, function(data) {

        var address = data.results[0].formatted_address;

        $("#caption").html(address);

        // get current weather conditions using JSONP on Dark Sky API
        $.ajax({
     url: weatherURL + lat + ',' + long + "?units=si",
          dataType: "jsonp",
          success: function (data) {

            // visualize data

            console.log(data.currently);
            $("#date").html(timeConverter(data.currently.time));
            $("#iTemp").html((data.currently.apparentTemperature).toFixed(1));
            $("#summary").html(data.currently.summary);

            var imgBackground = 'url(https://source.unsplash.com/' + background[data.currently.icon] + '/1600x900)';
            console.log(imgBackground);
            $('body').css('background-image', imgBackground);

            var skycons = new Skycons({"color": "white"});
            skycons.set("icon1", data.currently.icon);
            skycons.play();
          }
        });
      });
    });
  } else {
  /* geolocation IS NOT available */
  }

  function timeConverter(UNIX_timestamp){
    var a = new Date(UNIX_timestamp * 1000);
    var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
    var year = a.getFullYear();
    var month = months[a.getMonth()];
    var date = a.getDate();
    var hour = (a.getHours() < 10 ? '0' : '') + a.getHours();
    var min = (a.getMinutes() < 10 ? '0' : '') + a.getMinutes();
    var time = date + ' ' + month + ' ' + year + ' ' + hour + ':' + min;

    return time;
  }

  $("#btn-unit").on("click", function() {
    if($("#cUnit").text() == "C")
    {
      $("#iTemp").html(($("#iTemp").text() * 9 / 5 + 32).toFixed(1));
      $("#cUnit").html("F");
    } else {
      $("#iTemp").html((($("#iTemp").text() - 32) * 5 / 9).toFixed(1));
      $("#cUnit").html("C");
    }
  });
});

var background store sets of ids of photos in the unsplsh.com. This is used to change the background according to the weather status. If it's raining it will display a rainy background, If it's sunny it will display a background according to. So the background will change according to the weather condition.

Check out the final project



Comments

Popular posts from this blog

Working with Yeoman

Let's take a look at Yeomen. Yeomen is not part of MEAN Stack but allow us to quickly get startup providing us with generators that can create starter temples. It helps to setup the links between some or all the components of MEAN Stack, without having to do it all by hand. We will be focusing  a developing an app with MEAN Stack in the tutorial. Let's begin installing Yeoman using npm . $npm install -g yo Now that yeoman is installed we can next install a generator with it. Let's head to yeoman . io website and click discover generators. We going to use the gulp-angular generator. It will save us a lot of time setting up some tedious tasks that make our development process much faster. Gulp allow us to automate tedious and dependent tasks which are moving files over to publish folder or linking libraries or packages that needed our app. Click the gulp-angular generator and we can see the dependencies we need to install in order to run it. So let's o...

Unit Testing with Mocha

Unit testing is the best way to uncover hidden bugs in your system. JavaScript Community has produced several testing frameworks that will help us with the task of writing Unit Tests. Some of them are Jasmin, Mocha, Jaster, Quint. These are all JavaScript Testing frameworks, that you can use to test JavaScript Code. Today we are going to focus on the Mocha testing framework. Let's go and install Mocha globally that we can use on any of our projects. $ npm install  -g mocha To run a Mocha test all you need is to type mocha. But you need to have directory named test. Before running mocha first make sure you have created a directory call test. $ mocha Now Mocha is ready to use. Now let's go and create our first test. Create a folder MochaTesting anywhere in your folder. This is the folder we are going to work. Inside that folder create a folder called test. Inside the test, folder create a file call my-test.js We are going to use Test Dri...

Lambda expressions in JAVA

The Best new feature of JAVA SE 8 is called project Lambda. This brings Java into the world of functional programming. In computer science terminology Lambda is an anonymous function, that is a function without a name. In Java all functions are members of classes and refer to as methods. A Lambda expressions let you define a class and a single method with very consisted task, like implementing an interface that has abstract method. It lets developers simplify and shorten their code making it more readerable  and maintaiable . Lets take look at few code snippets. Priority it Java SE 8, if you want to create thread  you first define a class and implements the runable insterface . This is the interface have single abstarct method  named run  and accpect no arguments. You might define the class in its own code file. File named MyRunnable.java and you might named and impement the single abstract method. public class MyRunnable impments ...