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 LayoutAdd 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.850612Now 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
Post a Comment