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

Getting Started with Git & GittHub

Creating a Git Project Git is a version control system that keeps track of the files in a project. In order to use git, we start by identifying a folder as a git repository. we do it by running init command in the folder. Before running the git command go to your project folder and create two files called file1.txt and file2.txt and add some sample text to it and save the file. Now open up the git command line in the project folder and type the following command. An easy way to is by right clicking anywhere inside your project folder and click git bash here. $ git init Checking Status Now we created a git repository. Now we can check the status of our repository by typing git status in the git terminal. $ git status You can see there are two files in red which called as untracked files. This is because we still didn't add any file to our git repository. Adding files to Git repository To add files to your git repository by simply typing git add file1.t

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 Driven Development. That mean

Introduction to MEAN Stack

MEAN stands for Mongo, Express, Angular and Node. In the world of modern software, we typically deal with frontend and backend. MEAN Stack includes both technologies for both sides frontend and backend. Mongo Mongo is a cross-platform document-oriented database. Meaning is not like more traditional SQL database. Which is where NoSQL term comes from, with that means Mongo DB Store JSON-like documents with dynamic schemas making it better and faster for some applications.Companies with large scale deployments of Mongo DB includes Adobe, eBay, LinkedIn and much more. There is no database we can call as the best. It depends on the type of the system. Mongo DB is one in many options. Mongo DB is good for developers who is familiar with JavaScript and JSON and also easy to start learning. Express Express or ExpresJS is Node JS web application framework. It's the server framework for NodeJS. It allows quick development of robust web APIs by providing the thin and performa