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 simp...

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...

What is an API?

What is an API? The definitions given by WIKIPEDIA - set of   Classes   definitions, protocols, and tools for building   application software. HowStuffWorks- set of programming instructions and standards for accessing a web based software application or web tool. Quora - A contract provided by one piece of computer software to another. If I was to answer that question I will simply say that API is an interface that hires the details of an implementation. For example, the interface retain on a computer has a power button. This is one function of the interface computer manufacture gives us. APIs are usually used for three things. They are used for Performing tasks. For example, we may use tutor’s API to search with reach from Sanfransico.  Retrieving data.  We may use face . -force to achieve receivers friend list.  Manipulating data.  For example, we use android API to add a new contact. What is a web API? A web API...