Local Weather App

In this example below you will see how to do a Local Weather App with some HTML / CSS and Javascript

Detects user locations thru IP powered by ip-api.com and the weather within their location powered by openweather.org. Background generates different images based on the location if available, if not, generateson generic images based on the weather powered by Flickr.

Thumbnail
This awesome code was written by codefly0817, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright codefly0817 ©
  • HTML
  • CSS
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>Local Weather App</title>
  <meta charset="utf-8">
  
  
      <link rel="stylesheet" href="css/style.css">

  
</head>

<body>

  <html>
<!-- Added head tag to append script_element.src --->
	  <head>
  	</head>
  
  	<body>
    <!-- TITLE/HEADER -->
    <div class="title-container">
      <h1 class="main-title">Weatherly</h1>
      <p class="sub-title">Your Weather News Daily</p>
    </div>
    
    <!--- DATA HOLDER --->
		    <section>
			      <h1 id="city">Weather Web App</h1>      
      			<p>
        <a id="temperature" href="#" onclick="switchUnits(); return false;" title="Click to switch between metric and imperial units"></a>
        <span id="weather">Loading...</span>
      </p>
    		</section>
    
    <!-- FOOTER --->
    <footer>
			      <p>Powered by 
        <a href="http://flickr.com/services/api/">Flickr</a>, <a href="http://openweathermap.org">Openweathermap.org</a> and <a href="http://ip-api.com/">ip-api.com</a>. Created by <a href="https://twitter.com/v2danl">@v2danL</a>. Credits to @fourtonfish for <a href="https://fourtonfish.makes.org/thimble/make-your-own-web-mashup-introduction-to-web-apis">this tutorial.</a> <a id="image-source" href="#">Image source</a>.
      </p>
		    </footer>
  	</body>
</html>
  
  

    <script  src="js/index.js"></script>




</body>

</html>

/*Downloaded from https://www.codeseek.co/codefly0817/local-weather-app-jbqxBw */
@import url(https://fonts.googleapis.com/css?family=Fredoka+One);
@import url(https://fonts.googleapis.com/css?family=Josefin+Sans);

body {
height: 100%;
margin: 0;
padding: 0;
font-family: Tahoma, Verdana sans-serif;
text-shadow: 0 0 10px #000;
color: #fff;
background: #888;
background-repeat: no-repeat;
background-attachment: fixed;
background-size: cover;
}

.title-container {
  text-align: center;
} 

.main-title {
  font-family: "Fredoka One", Verdana, Tahoma, sans-serif;
  font-size: 5em;
  margin: 0 0 -30px;
}

.sub-title {
  font-family: "Josefin Sans", Verdana, Tahoma, sans-serif;
  font-size: 1.5em;
}

section {
  min-height: 100%;
  background: -webkit-linear-gradient(to left, rgba(0,0,0,0), rgba(0,0,0,0), rgba(255,255,255,.3)); /* For Safari 5.1 to 6.0 */
  background: -o-linear-gradient(to left, rgba(0,0,0,0), rgba(0,0,0,0), rgba(255,255,255,.3)); /* For Opera 11.1 to 12.0 */
  background: -moz-linear-gradient(to left, rgba(0,0,0,0), rgba(0,0,0,0), rgba(255,255,255,.3)); /* For Firefox 3.6 to 15 */
  background: linear-gradient(to left, rgba(0,0,0,0), rgba(0,0,0,0), rgba(255,255,255,.3)); /* Standard syntax */
}

section h1 {
  font-size: 5em;
  padding: 0.1em 0.3em;
  line-height: 1em;
  margin-bottom: -.4em;
}

section p {
  padding: 0 1em 0.1em;
  font-size: 4em;
}

a {
  color: #fff;
}

#temperature {
  text-decoration: none;
  color: rgb(100,200,255);
}

#temperature:hover {
  text-shadow: 0 0 10px teal;
}

footer {
  position: absolute;
  bottom: 0;
  font-size: 0.8em;
  padding: 0 1em;
}

footer a {
  text-decoration: none;
  color: rgb(100,200,255);
}

footer a:hover {
  text-shadow: 0 0 10px teal;
}

/*Downloaded from https://www.codeseek.co/codefly0817/local-weather-app-jbqxBw */
//Data Storage
var weatherData = {
  city: document.querySelector("#city"),
  weather:  document.querySelector("#weather"),
  temperature: document.querySelector("#temperature"),
  temperatureValue: 0,
  units: "°C"
};

//Round temperature decimals
function roundTemperature(temperature)  {
  temperature =+ temperature.toFixed(2);
  return temperature;
};

//Toggle Celsius and Fahrenheit units
function switchUnits() {
  if (weatherData.units == "°C") {
    weatherData.temperatureValue = roundTemperature(weatherData.temperatureValue * 9/5 + 32);
    weatherData.units = "°F";
  } else {
	  weatherData.temperatureValue = roundTemperature((weatherData.temperatureValue -  32) * 5/9);
		weatherData.units = "°C";
  };
    weatherData.temperature.innerHTML = weatherData.temperatureValue + weatherData.units;			
  }

function getLocationAndWeather() {
  if (window.XMLHttpRequest) {
    var xhr = new XMLHttpRequest();
    
    xhr.addEventListener("load", function() {
    console.log("Processing weather info...");
      
    var response = JSON.parse(xhr.responseText);
    console.log(response);
      
    var position = {
						latitude: response.latitude,
						longitude: response.longitude
    };
      
    var cityName = response.city;
    
    if (cityName == "Earth") {
						// If IP-based location detection failed. Ask the user where they live
      getWeatherForLocation();
    }	else {
      
      var weatherSimpleDescription = response.weather.simple;
			var weatherDescription = response.weather.description;
      //Note: rounding the temperature here is only necessary when starting with Celsius as your default unit.
      var weatherTemperature = roundTemperature(response.weather.temperature);
			/* To keep things clean, we don't really need to store the values above in the memory, so we're defining them as local variables. As such, they will be cleared after this function runs. However, we will need to save the temperature globally in order to do conversions. */
      weatherData.temperatureValue = weatherTemperature;

      loadBackground(position.latitude, position.longitude, weatherSimpleDescription);
			weatherData.city.innerHTML = cityName;
			weatherData.weather.innerHTML =  ", " + weatherDescription;
			weatherData.temperature.innerHTML = weatherTemperature + weatherData.units;
			console.log("Finished processing and displaying weather info.");
		  }
    }, false);

        xhr.addEventListener("error", function(err) {
					alert("Could not complete the request");
				}, false);

				xhr.open("GET", "https://fourtonfish.com/tutorials/weather-web-app/getlocationandweather.php?owapikey=0645b1903bba932dbdc77ec00d9bbed8&units=metric", true);
				xhr.send();
				console.log("Requesting weather info...");
			}
			else{
				alert("Unable to fetch data at the moment. Please try again later.");
			}						
		}

		function getWeatherForLocation() {
			var location = prompt("Your location could not be detected automatically, can you tell me where you live?");
			if (location != null){
				document.querySelector("body").style.backgroundImage = "url('https://fourtonfish.com/tutorials/weather-web-app/images/default.jpg')";
				document.querySelector("#image-source").setAttribute("href", "https://www.flickr.com/photos/superfamous/310185523/sizes/o/");
				
				var xhr = new XMLHttpRequest();
				xhr.addEventListener("load", function() {
					var response = JSON.parse(xhr.responseText);

					console.log(response);
					var position = {
						latitude: response.latitude,
						longitude: response.longitude
					};
					var cityName = response.city;

					var weatherSimpleDescription = response.weather.simple;
					var weatherDescription = response.weather.description;
					var weatherTemperature = roundTemperature(response.weather.temperature);
					weatherData.temperatureValue = weatherTemperature;

					weatherData.city.innerHTML = cityName;
					weatherData.weather.innerHTML =  ", " + weatherDescription;
					weatherData.temperature.innerHTML = weatherTemperature + weatherData.units;					
				}, false);

				xhr.addEventListener("error", function(err){
					alert("Could not complete the request.");
				}, false);



				xhr.open("GET", "https://fourtonfish.com/tutorials/weather-web-app/getweatherforlocation.php?owapikey=45713cc0d54c4bfa1c7efbbdbd1c6c2b&units=metric&location=" + location, true);
				xhr.send();
			}
			else{
				alert("Unable to fetch data at the moment. Please try again later.");
			}						
		}

//Load Background based on Location fetch by Latitude & Longitude
function loadBackground(lat, lon, weatherTag) {
  var script_element = document.createElement('script');

	script_element.src = "https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=434d86456cc3b57d1fe1e9c2e5053702&lat=" + lat + "&lon=" + lon + "&accuracy=1&tags=" + weatherTag + "&sort=relevance&extras=url_l&format=json";

  document.getElementsByTagName('head')[0].appendChild(script_element);
}

function jsonFlickrApi(data) {
  console.log(data);
    if (data.photos.pages > 0) {
      var photo = data.photos.photo[0];
				document.querySelector("body").style.backgroundImage = "url('" + photo.url_l + "')";
        document.querySelector("#image-source").setAttribute("href", "http://www.flickr.com/photos/" + photo.owner + "/" + photo.id);
    } else {
				document.querySelector("body").style.backgroundImage = "url('https://fourtonfish.com/tutorials/weather-web-app/images/default.jpg')";
				document.querySelector("#image-source").setAttribute("href", "https://www.flickr.com/photos/superfamous/310185523/sizes/o/");
    }
}

		//To wrap it up
		getLocationAndWeather();

Comments