Complete tutorial on making a Web App to check Live Weather conditions!


07 Jul 2018views: 399


blog cover image

Web Apps are the future of Web. There are absouletely no difference betweeen modern Web Apps and native Android/IOS apps. With the advancement of Web technologies the possibilities is endless.

Here is the step by step tutorial on making a Web App to check Live Weather conditions using Yahoo Weather API, HTML and Javascript. The project is live at techconductor/weather check out this first.

The core is the Yahoo Weather API from which all the weather information is fetched using Ajax. To extend the functionality Auto Detect feature is also used similar to this post. which uses Geolocation and Google Maps API to get user city information.

The design is inspired by this codepen. The mechanism behind the entire process is that first the defult layout is displayed then using Ajax weather information in fetched from Yahoo Weather API and then the result is extracted from the JSON response and then displayed on the specific locations.

HTML

The entire project is also available on GitHub

The HTML part is simple, the card design has two parts front and back. All the specific tags has an id attribute so that the information on that tag can be updated using Javascript.

<div class="container">
  <div class="row">
    <div class="col-12"><br>
    <div class="card-container">
      <div class="card">
        <div class="front">
          <div class="pl-5 pr-5" id="weather_wrapper">
            <div class="weatherCard shadowDepthNav">
              <div class="currentTemp">
                <span id="temp" class="temp pl-5"> 29&deg;</span>
                <span id="location" class="location">Guwahati</span>
              </div>
            </div>
            <div class="weatherCard shadowDepthNav">
              <div class="currentWeather">
                <i id="w_icon" class="wi wi-yahoo-26 conditions"></i>
                <p id="report" class="text-center pt-4"></p>
                <div class="info">
                  <span id="humid" class="humid">45</span>
                  <span id="wind" class="wind">06 KPH</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="back">
          <div class="pl-5 pr-5" id="weather_wrapper">
            <div class="weatherCard shadowDepthNav p-2">
              <div id="forcast" class="currentTemp text-center">
              </div>
            </div>
            <div class="weatherCard shadowDepthNav">
              <div class="currentWeather">
                <i id="w_icon_b" class="wi wi-yahoo-26 conditions"></i>
                <p id="report_b" class="text-center pt-4"></p>
                <div class="info">
                  <span id="sunrise" class="sunrise">00:00</span>
                  <span id="sunset" class="sunset">00:00</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <br>
  <div class="form-container">
    <form class="form-group mx-sm-3 mb-2" id="subs_form" method="GET">

        <!-- CITY -->
        <div id="city-group" class="form-group">
            <input type="text" class="form-control" name="city" id="city" placeholder="City">
        </div>

        <button id="submit" type="submit" name="submit" class="btn btn-success mb-2">Submit <span class="fa fa-arrow-right"></span></button>
        <button id="auto_detect" name="auto_detect" onclick="getLocation()" class="btn btn-info mb-2">Auto Detect</button>

    </form>
    <div id="result"></div>
    <div id="loc_lat_lng"></div>
    </div><br><br>
  </div>
</div>
</div>


Javascript

Here two script is used one for fetching weather information from the Yahoo Weather API and to update the information on the display. Another script handles the Auto Detect feature and uses Geolocation and Google Maps API to get the location information.

The App has two buttons on to manualy submit the city name and another to Auto Detect the location. The first script handles the submit button and the second script handles the Auto Detect button.

So when the user inputs the city name and clicks on Submit button the first scripts makes an Ajax call to Yahoo Weather API along with the formData which holds the city name. Then .done(function(data) handles the response from the Yahoo Weather API and data holds the entire JSON response. console.log(data) is used to view the JSON data on the browser console.

Next all the specific variables are made which holds specific informations. Then Jquery is used to display those data on the specific HTML tags. To display the forecast data from the JSON array for loop is used.

<script type="text/javascript">
  $(document).ready(function() {

    $('form').submit(function(event) {

      var formData = {
          'city': $('input[name=city]').val()
      };
      console.log(formData);
      if(formData.city == ""){
        console.log('empty City name!');
      }else{
        // process the form
        $.ajax({
            type        : 'GET', 
            url         : 'https://query.yahooapis.com/v1/public/yql?q=select%20units,astronomy,atmosphere,wind,location,item%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text=%22'+formData.city+'%22)%20and%20u=%22c%22&format=json',
            data        : formData, // our data object
            dataType    : 'json',
            encode      : true
        })
          // using the done promise callback
          .done(function(data) {

            console.log(data)
            //extract individual information ffrom the JSON response
            var temperature = data.query.results.channel.item.condition.temp;
            var place = data.query.results.channel.location.city;
            var wind = data.query.results.channel.wind.speed;
            var last_update = data.query.results.channel.item.title;
            var report = data.query.results.channel.item.condition.text;
            var icon_code = data.query.results.channel.item.condition.code;
            var humidity = data.query.results.channel.atmosphere.humidity;
            var sunrise = data.query.results.channel.astronomy.sunrise;
            var sunset = data.query.results.channel.astronomy.sunset;

            //display our fetched information
            $('#temp').empty();
            $("#temp").append(' '+temperature+'&deg;');
            $('#location').empty();
            $("#location").append(place);
            $("#wind").empty();
            $("#wind").append(wind+' KPH');
            $("#result").empty();
            $("#result").append('Updated: '+last_update);
            $("#report").empty();
            $("#report").append(report);
            $("#w_icon").removeClass();
            $("#w_icon").addClass('wi wi-yahoo-'+icon_code+' conditions');
            $("#report_b").empty();
            $("#report_b").append(report);
            $("#w_icon_b").removeClass();
            $("#w_icon_b").addClass('wi wi-yahoo-'+icon_code+' conditions');
            $("#humid").empty();
            $("#humid").append(humidity); 
            $("#sunrise").empty();
            $("#sunrise").append(sunrise);
            $("#sunset").empty();
            $("#sunset").append(sunset);
            $("#forcast").empty();
            var i;
            for (i = 0; i < 7; i++) {
             $("#forcast").append('<p class="text-white">'+data.query.results.channel.item.forecast[i].day+' : '+data.query.results.channel.item.forecast[i].high+'<sup>o</sup>C - '+data.query.results.channel.item.forecast[i].low+'<sup>o</sup>C <spam class="wi wi-yahoo-'+data.query.results.channel.item.forecast[i].code+' pl-3"></spam></p>');   
            }           
          });
      }

        // stop the form from submitting the normal way and refreshing the page
        event.preventDefault();
    });
});
</script>


When the user clicks on the Auto Detect button the second script handles the request and uses the Geolocation API to get the users current Latitude and Longitude then Ajax GET request is made to the Google Maps API to get the users city name using Latitude and Longitude data from Geolocation API.

This is similar to the script used on this post. Only difference is that here only city name is fetched from the JSON response and then the city name is added to the form input tag value field using Jquery and the again using Jquery the form is submitted.

<script type="text/javascript">
function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
  } else { 
    temp_lat = 0.0; //set default lat value
    temp_lng = 0.0; //set default lng value
  }
}

function showPosition(position) {
  temp_lat = position.coords.latitude;
  temp_lng = position.coords.longitude;
  $("#loc_lat_lng").html('<p align="justify"><b>Lat:</b>'+temp_lat+' <b>Lng:</b> '+temp_lng+'</p>');
  $.ajax({
    type        : 'GET', 
    url         : 'https://maps.googleapis.com/maps/api/geocode/json?latlng='+temp_lat+','+temp_lng+'&sensor=true',
    dataType    : 'json',
    encode      : true
  })
  .done(function(data) {

    if(data.status === "OK"){
      var addr_array_length = data.results[0].address_components.length;
      var c = data.results[0].address_components[addr_array_length - 5].long_name;
      $("#city").val(c);
      $("#subs_form").submit();
    }else{
      console.log('Oops!');
    }
  });
}
</script>


The remaning HTML part and CSS is available on GitHub. Hope that was helpful if found interesting do share and Like the post. Also Click on the floating bell icon to get notifications on new posts.




Thank you for Subscribing! We will make sure you never miss a thing.



author-avatar

Om Prakash Mahato

Full stack developer, author, founder of TechConductor.


0 Comments:


    Leave a comment:


    Name is ok.
    Comment is ok.
    Email is ok.
    Website is ok.