Local Weather App

JavaScript
//get date object
var date = new Date();
var hour = date.getHours();

jQuery(document).ready(function () {

  function getLocation() {
    //credit to W3schools.com for geolocation code
    //if a geolocation object exists...
    if (navigator.geolocation) {
      //call the object's getCurrentPosition() method; once a position is obtained, execute the callback function showPosition, and in the event a geolocation error occurs, execute the callback function showError
      navigator.geolocation.getCurrentPosition(showPosition, showError);
    }
    //if a geolocation object does not exist...
    else {
      jQuery('#details-container').css('display', 'block');
      jQuery('.weather-title').html('<span>Geolocation is not supported by your browser.<span>');
      jQuery('#veil').css('display', 'none');
    }
  }

  //the callback function which uses the geolocation object to display the weather
  function showPosition(position) {

    jQuery('#details-container').css('display', 'block');

    var lat = position.coords.latitude;
    var lon = position.coords.longitude;

    var weatherURL = "https://cors-anywhere.herokuapp.com/http://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + lon + "&APPID=KEYGOESHERE";

    //get weather object from open weather api
    jQuery.getJSON(weatherURL, function (json) {

      jQuery('#toggle-temp').addClass('wpforms-submit').css('display', 'block');

      jQuery('.weather-title').html('<span> Current Weather Report for ' + json["name"] + ':' + '</span>');

      jQuery('.conditions').html('<span>' + json["weather"][0]["description"] + '</span>');

      var weatherID = json["weather"][0]["id"];
      var baseURL = "https://openweathermap.org/img/w/";

      //if it is night based on the date object, do the following...
      if ((hour >= 0 && hour <= 5) || (hour >= 18 && hour <= 23)) {
        console.log("It's night (b/t midnight and 5:59am or b/t 6pm and 11:59pm)");

        //display a semi-transparent black layer over the weather image for night effect
        jQuery('#veil').css('display', 'block');

        //dispay a different weather background image and weather icon for each of six weather categories
        switch (true) {
        case (weatherID >= 200 && weatherID <= 232): //thunderstorm
          jQuery('#weatherIcon').attr('src', baseURL + "11n.png");
          jQuery('#weather-report').css('background-image', 'url(https://resultswebsitedesign.com/wp-content/uploads/2017/05/thunderstorm1080x720.jpg)');
          break;
        case ((weatherID >= 300 && weatherID <= 321) || (weatherID >= 500 && weatherID <= 531)): //"drizzle" or "rain" respectively, using same pic
          jQuery('#weatherIcon').attr('src', baseURL + "09n.png");
          jQuery('#weather-report').css('background-image', 'url(https://resultswebsitedesign.com/wp-content/uploads/2017/05/rain1080x760.jpg)');
          break;
        case (weatherID >= 600 && weatherID <= 622): //snow
          jQuery('#weatherIcon').attr('src', baseURL + "13n.png");
          jQuery('#weather-report').css('background-image', 'url(https://resultswebsitedesign.com/wp-content/uploads/2017/05/snow1080x810.jpg)');
          break;
        case (weatherID >= 701 && weatherID <= 781): //mist, smoke, haze, sand/dust whirls, fog, dust, volcanic ash, squalls, tornado
          jQuery('#weatherIcon').attr('src', baseURL + "50n.png");
          jQuery('#weather-report').css('background-image', 'url(https://resultswebsitedesign.com/wp-content/uploads/2017/05/windmill1080x810.jpg)');
          break;
        case (weatherID === 800): //clear
          jQuery('#weatherIcon').attr('src', baseURL + "01n.png");
          jQuery('#weather-report').css('background-image', 'url(https://resultswebsitedesign.com/wp-content/uploads/2017/05/clear1080x720.jpg)');
          break;
        case (weatherID >= 801 && weatherID <= 804): //clouds
          jQuery('#weatherIcon').attr('src', baseURL + "03n.png");
          jQuery('#weather-report').css('background-image', 'url(https://resultswebsitedesign.com/wp-content/uploads/2017/05/cloudy1080x720.jpg)');
          break;
        }

        //if it is day based on the date object, do the following...
      } else {
        console.log("it's day");

        //dispay a different weather background image and weather icon for each of six weather categories
        switch (true) {
        case (weatherID >= 200 && weatherID <= 232): //thunderstorm
          jQuery('#weatherIcon').attr('src', baseURL + "11d.png");
          jQuery('#weather-report').css('background-image', 'url(https://resultswebsitedesign.com/wp-content/uploads/2017/05/thunderstorm1080x720.jpg)');
          break;
        case ((weatherID >= 300 && weatherID <= 321) || (weatherID >= 500 && weatherID <= 531)): //"drizzle" or "rain" respectively, using same pic
          jQuery('#weatherIcon').attr('src', baseURL + "09d.png");
          jQuery('#weather-report').css('background-image', 'url(https://resultswebsitedesign.com/wp-content/uploads/2017/05/rain1080x760.jpg)');
          break;
        case (weatherID >= 600 && weatherID <= 622): //snow
          jQuery('#weatherIcon').attr('src', baseURL + "13d.png");
          jQuery('#weather-report').css('background-image', 'url(https://resultswebsitedesign.com/wp-content/uploads/2017/05/snow1080x810.jpg)');
          break;
        case (weatherID >= 701 && weatherID <= 781): //mist, smoke, haze, sand/dust whirls, fog, dust, volcanic ash, squalls, tornado
          jQuery('#weatherIcon').attr('src', baseURL + "50d.png");
          jQuery('#weather-report').css('background-image', 'url(https://resultswebsitedesign.com/wp-content/uploads/2017/05/windmill1080x810.jpg)');
          break;
        case (weatherID === 800): //clear
          jQuery('#weatherIcon').attr('src', baseURL + "01d.png");
          jQuery('#weather-report').css('background-image', 'url(https://resultswebsitedesign.com/wp-content/uploads/2017/05/sunny1080x723.jpg)');
          break;
        case (weatherID >= 801 && weatherID <= 804): //clouds
          jQuery('#weatherIcon').attr('src', baseURL + "03d.png");
          jQuery('#weather-report').css('background-image', 'url(https://resultswebsitedesign.com/wp-content/uploads/2017/05/cloudy1080x720.jpg)');
          break;
        }
      }

      //convert source Kelvin temp to Fahrenheit and Celsius
      var kelvinTemp = json["main"]["temp"];
      var fahrTemp = Math.round(((kelvinTemp - 273.15) * (9 / 5)) + 32);
      var celsTemp = Math.round(kelvinTemp - 273.15);

      //display Fahrenheit temp by default
      jQuery('#temp-report').html("Temperature: " + fahrTemp + "°" + " F");

      //when the toggle-temp button is clicked, check to see if it reads Celsius or Fahrenheit
      jQuery('button#toggle-temp').click(function () {

        //if the button reads "Celsius"...
        if (jQuery('button#toggle-temp:contains(Celsius)').length !== 0) {
          //display the temp in Celsius
          jQuery('#temp-report').html('Temperature: ' + celsTemp + '°' + ' C');
          //make the button text read "to Fahrenheit"
          jQuery('button#toggle-temp').html('to Fahrenheit');
        }
        //if the button reads "Fahrenheit"...
        else if (jQuery('button#toggle-temp:contains(Fahrenheit)').length !== 0) {
          //display the temp in Fahrenheit
          jQuery('#temp-report').html('Temperature: ' + fahrTemp + '°' + ' F');
          //make the button text read "to Celsius"
          jQuery('button#toggle-temp').html('to Celsius');
        }
      });
    });
  }
  getLocation();

  //callback function which handles getGeolocation() errors    
  function showError(error) {
    //credit to W3schools.com for error handling
    jQuery('#toggle-temp').css('display', 'none');
    jQuery('#details-container').css('display', 'block');
    switch (error.code) {
    case error.PERMISSION_DENIED:
      jQuery('.weather-title').html('<span>Your settings denied the request for geolocation.  Please allow geolocation in your browser and/or OS settings so your local weather may be displayed.<span>');
      jQuery('#veil').css('display', 'none');
      break;
    case error.POSITION_UNAVAILABLE:
      jQuery('.weather-title').html('<span>Location information is unavailable, so the weather for your location cannot be displayed.<span>');
      jQuery('#veil').css('display', 'none');
      break;
    case error.TIMEOUT:
      jQuery('.weather-title').html('<span>The request to get your location timed out, so weather for your location cannot be displayed.<span>');
      jQuery('#veil').css('display', 'none');
      break;
    case error.UNKNOWN_ERROR:
      jQuery('.weather-title').html('<span>An unknown error occurred, so weather for your location cannot be displayed. <span>');
      //    jQuery('#weather-report').css('background-image', 'url(https://resultswebsitedesign.com/wp-content/uploads/2017/06/geolocation1080x720.jpg)');
      jQuery('#veil').css('display', 'none');
      break;
    }
  }

  //prevent default api service failure message from flashing before a successful api call can complete and populate the widget
  setTimeout(function () {

    //detect if .weather-title has been populated due to successful api call or geolocation error info
    if (jQuery('.weather-title').text().length === 0) {

      jQuery('.weather-title').html('<span>An API service required to fetch the weather for your location is temporarily unavailable.  Please try again later.<span>');
    }
  }, 1000);
});
CSS
  .weather-title {
    text-align: center;
    padding-top: 15px;
  }  
  .conditions {
    text-align: center;
    text-transform: capitalize;
  } 
  .flex-container {
    display: flex;
    justify-content: center;
    width: 100%;
  } 
  #weather-report {
    max-width: 1080px;
    width: 100%;
    margin: 0 auto;
    padding: 0 15px;
    min-height: 720px;
    position: relative;
    border-radius: 10px;
    background-position: center;
  } 
  #veil,
  #default-background {
    width: 100%;
    min-height: 720px;
    position: absolute;
    top: 0;
    left: 0;
    border-radius: 10px;
  }  
  #veil {
    background-color: rgba(0, 0, 0, .5);
    z-index: 1;
    display: none;
  }  
  #default-background {
    z-index: -1;
    background: url(https://resultswebsitedesign.com/wp-content/uploads/2017/06/geolocation1080x720.jpg) center;
    display: block;
  }
  #details-container {
    /*prevent display until it is known whether geolocation is allowed*/
    display: none;
    position: relative;
    /*position weather details in layer above veil*/
    z-index: 2;
    max-width: 500px;
    background: rgba(255, 255, 255, .5);
    padding: 0 10px;
    margin: 0 auto;
    border-radius: 10px;
    top: 15px;
  } 
  #toggle-temp {
    /*prevent display until it is known whether geolocation is allowed*/
    display: none;
  }

Leave a Reply

Your email address will not be published. Required fields are marked *