Skip to content

Instantly share code, notes, and snippets.

@chemok78
Created July 22, 2016 06:25
Show Gist options
  • Save chemok78/23a9dad313e12d810e11528bce77c43f to your computer and use it in GitHub Desktop.
Save chemok78/23a9dad313e12d810e11528bce77c43f to your computer and use it in GitHub Desktop.
Weather App
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>What is the Weather?</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<link href='https://fonts.googleapis.com/css?family=Merriweather:400,700' rel='stylesheet' type='text/css'>
</head>
<body>
<div class="container">
<div class="well well-sm">
<h1 class="text-center">Weather?</h1>
<p style="font-style: italic" class="text-center">Your weather + random image for your location</p>
<div class="text-center">
<h4 id="location">Getting your location...</h4>
<div id="toggleTemperature">
<h4 id="temperature"></h4>
<h4 id="temperatureF"></h4>
</div>
<h4 id="weatherStatus"></h4>
<h4><i id="weatherSymbol"></i></h4>
<button class="btn btn-primary" id="newBackground">Change Background</button>
</div>
</div id="box" class="container">
<p class="photographer">Photos by <a href="http://www.unsplash.com">Unsplash</a></p>
</div>
</div>
</body>
<html>
$(document).ready(function() {
var isoCountries = {
'AF': 'Afghanistan',
'AX': 'Aland Islands',
'AL': 'Albania',
'DZ': 'Algeria',
'AS': 'American Samoa',
'AD': 'Andorra',
'AO': 'Angola',
'AI': 'Anguilla',
'AQ': 'Antarctica',
'AG': 'Antigua And Barbuda',
'AR': 'Argentina',
'AM': 'Armenia',
'AW': 'Aruba',
'AU': 'Australia',
'AT': 'Austria',
'AZ': 'Azerbaijan',
'BS': 'Bahamas',
'BH': 'Bahrain',
'BD': 'Bangladesh',
'BB': 'Barbados',
'BY': 'Belarus',
'BE': 'Belgium',
'BZ': 'Belize',
'BJ': 'Benin',
'BM': 'Bermuda',
'BT': 'Bhutan',
'BO': 'Bolivia',
'BA': 'Bosnia And Herzegovina',
'BW': 'Botswana',
'BV': 'Bouvet Island',
'BR': 'Brazil',
'IO': 'British Indian Ocean Territory',
'BN': 'Brunei Darussalam',
'BG': 'Bulgaria',
'BF': 'Burkina Faso',
'BI': 'Burundi',
'KH': 'Cambodia',
'CM': 'Cameroon',
'CA': 'Canada',
'CV': 'Cape Verde',
'KY': 'Cayman Islands',
'CF': 'Central African Republic',
'TD': 'Chad',
'CL': 'Chile',
'CN': 'China',
'CX': 'Christmas Island',
'CC': 'Cocos (Keeling) Islands',
'CO': 'Colombia',
'KM': 'Comoros',
'CG': 'Congo',
'CD': 'Congo, Democratic Republic',
'CK': 'Cook Islands',
'CR': 'Costa Rica',
'CI': 'Cote D\'Ivoire',
'HR': 'Croatia',
'CU': 'Cuba',
'CY': 'Cyprus',
'CZ': 'Czech Republic',
'DK': 'Denmark',
'DJ': 'Djibouti',
'DM': 'Dominica',
'DO': 'Dominican Republic',
'EC': 'Ecuador',
'EG': 'Egypt',
'SV': 'El Salvador',
'GQ': 'Equatorial Guinea',
'ER': 'Eritrea',
'EE': 'Estonia',
'ET': 'Ethiopia',
'FK': 'Falkland Islands (Malvinas)',
'FO': 'Faroe Islands',
'FJ': 'Fiji',
'FI': 'Finland',
'FR': 'France',
'GF': 'French Guiana',
'PF': 'French Polynesia',
'TF': 'French Southern Territories',
'GA': 'Gabon',
'GM': 'Gambia',
'GE': 'Georgia',
'DE': 'Germany',
'GH': 'Ghana',
'GI': 'Gibraltar',
'GR': 'Greece',
'GL': 'Greenland',
'GD': 'Grenada',
'GP': 'Guadeloupe',
'GU': 'Guam',
'GT': 'Guatemala',
'GG': 'Guernsey',
'GN': 'Guinea',
'GW': 'Guinea-Bissau',
'GY': 'Guyana',
'HT': 'Haiti',
'HM': 'Heard Island & Mcdonald Islands',
'VA': 'Holy See (Vatican City State)',
'HN': 'Honduras',
'HK': 'Hong Kong',
'HU': 'Hungary',
'IS': 'Iceland',
'IN': 'India',
'ID': 'Indonesia',
'IR': 'Iran, Islamic Republic Of',
'IQ': 'Iraq',
'IE': 'Ireland',
'IM': 'Isle Of Man',
'IL': 'Israel',
'IT': 'Italy',
'JM': 'Jamaica',
'JP': 'Japan',
'JE': 'Jersey',
'JO': 'Jordan',
'KZ': 'Kazakhstan',
'KE': 'Kenya',
'KI': 'Kiribati',
'KR': 'Korea',
'KW': 'Kuwait',
'KG': 'Kyrgyzstan',
'LA': 'Lao People\'s Democratic Republic',
'LV': 'Latvia',
'LB': 'Lebanon',
'LS': 'Lesotho',
'LR': 'Liberia',
'LY': 'Libyan Arab Jamahiriya',
'LI': 'Liechtenstein',
'LT': 'Lithuania',
'LU': 'Luxembourg',
'MO': 'Macao',
'MK': 'Macedonia',
'MG': 'Madagascar',
'MW': 'Malawi',
'MY': 'Malaysia',
'MV': 'Maldives',
'ML': 'Mali',
'MT': 'Malta',
'MH': 'Marshall Islands',
'MQ': 'Martinique',
'MR': 'Mauritania',
'MU': 'Mauritius',
'YT': 'Mayotte',
'MX': 'Mexico',
'FM': 'Micronesia, Federated States Of',
'MD': 'Moldova',
'MC': 'Monaco',
'MN': 'Mongolia',
'ME': 'Montenegro',
'MS': 'Montserrat',
'MA': 'Morocco',
'MZ': 'Mozambique',
'MM': 'Myanmar',
'NA': 'Namibia',
'NR': 'Nauru',
'NP': 'Nepal',
'NL': 'Netherlands',
'AN': 'Netherlands Antilles',
'NC': 'New Caledonia',
'NZ': 'New Zealand',
'NI': 'Nicaragua',
'NE': 'Niger',
'NG': 'Nigeria',
'NU': 'Niue',
'NF': 'Norfolk Island',
'MP': 'Northern Mariana Islands',
'NO': 'Norway',
'OM': 'Oman',
'PK': 'Pakistan',
'PW': 'Palau',
'PS': 'Palestinian Territory, Occupied',
'PA': 'Panama',
'PG': 'Papua New Guinea',
'PY': 'Paraguay',
'PE': 'Peru',
'PH': 'Philippines',
'PN': 'Pitcairn',
'PL': 'Poland',
'PT': 'Portugal',
'PR': 'Puerto Rico',
'QA': 'Qatar',
'RE': 'Reunion',
'RO': 'Romania',
'RU': 'Russian Federation',
'RW': 'Rwanda',
'BL': 'Saint Barthelemy',
'SH': 'Saint Helena',
'KN': 'Saint Kitts And Nevis',
'LC': 'Saint Lucia',
'MF': 'Saint Martin',
'PM': 'Saint Pierre And Miquelon',
'VC': 'Saint Vincent And Grenadines',
'WS': 'Samoa',
'SM': 'San Marino',
'ST': 'Sao Tome And Principe',
'SA': 'Saudi Arabia',
'SN': 'Senegal',
'RS': 'Serbia',
'SC': 'Seychelles',
'SL': 'Sierra Leone',
'SG': 'Singapore',
'SK': 'Slovakia',
'SI': 'Slovenia',
'SB': 'Solomon Islands',
'SO': 'Somalia',
'ZA': 'South Africa',
'GS': 'South Georgia And Sandwich Isl.',
'ES': 'Spain',
'LK': 'Sri Lanka',
'SD': 'Sudan',
'SR': 'Suriname',
'SJ': 'Svalbard And Jan Mayen',
'SZ': 'Swaziland',
'SE': 'Sweden',
'CH': 'Switzerland',
'SY': 'Syrian Arab Republic',
'TW': 'Taiwan',
'TJ': 'Tajikistan',
'TZ': 'Tanzania',
'TH': 'Thailand',
'TL': 'Timor-Leste',
'TG': 'Togo',
'TK': 'Tokelau',
'TO': 'Tonga',
'TT': 'Trinidad And Tobago',
'TN': 'Tunisia',
'TR': 'Turkey',
'TM': 'Turkmenistan',
'TC': 'Turks And Caicos Islands',
'TV': 'Tuvalu',
'UG': 'Uganda',
'UA': 'Ukraine',
'AE': 'United Arab Emirates',
'GB': 'United Kingdom',
'US': 'United States',
'UM': 'United States Outlying Islands',
'UY': 'Uruguay',
'UZ': 'Uzbekistan',
'VU': 'Vanuatu',
'VE': 'Venezuela',
'VN': 'Viet Nam',
'VG': 'Virgin Islands, British',
'VI': 'Virgin Islands, U.S.',
'WF': 'Wallis And Futuna',
'EH': 'Western Sahara',
'YE': 'Yemen',
'ZM': 'Zambia',
'ZW': 'Zimbabwe'
};
var weatherIcons = {
'01d': 'wi wi-day-sunny',
'02d': 'wi wi-day-cloudy',
'03d': 'wi wi-cloud',
'04d': 'wi wi-cloudy',
'09d': 'wi wi-showers',
'10d': 'wi wi-day-rain',
'11d': 'wi wi-day-thunderstorm',
'13d': 'wi wi-day-snow',
'50d': 'wi wi-day-fog',
'01n': 'wi wi-night-clear',
'02n': 'wi wi-night-alt-cloudy',
'03n': 'wi wi-cloud',
'04n': 'wi wi-cloudy',
'09n': 'wi wi-night-alt-showers',
'10b': 'wi wi-night-alt-rain',
'11n': 'wi wi-night-alt-thunderstorm',
'13n': 'wi wi-night-alt-snow',
'50n': 'wi wi-night-fog',
}
function setWeatherSymbol(symbol) { //change openweather symbol code to weathericon.io class names
if (weatherIcons.hasOwnProperty(symbol)) {
$('#weatherSymbol').addClass(weatherIcons[symbol]);
} else {
return symbol;
}
}
function getCountryName(countryCode) { //convert country code to full country name
if (isoCountries.hasOwnProperty(countryCode)) {
currentWeather.country = isoCountries[countryCode];
} else {
return countryCode;
}
}
function changeImage(query) {
/*change background image based on location using a random photo Unsplash.
Called within setWeather function, in success callback when weather retrieved*/
$.ajax({
url: "https://api.unsplash.com/photos/random?client_id=a1e9aefe055126e6ca4d1a52c79652cf8bc30e7cb4a690f19b937db4d3f87c09&query=" + query,
cache: false,
success: function(result) {
randomPhoto = result.urls.full;
photoName = result.user.name;
photoLocation = result.location.country;
photoCity = result.location.city;
$('body').css('background-image', 'url(' + randomPhoto + ')');
if(photoCity === null){
$('.photographer').html('Weather & Images &copy by Che Mug | Photo by ' + photoName + ' | ' + photoLocation);
} else {
$('.photographer').html('Weather & Images &copy by Che Mug | Photo by ' + photoName + ' | ' + photoCity + ', ' + photoLocation);
}
}
});
}
var latitude = 0;
var longitude = 0;
var currentWeather = {}; //initialize global variable, object to hold weather data
function setCoordinates(callback) { //get position. Callback function waits for this to execute and then uses position as argument.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(callback);
}
}
function setWeather(position) { //function to execute after getting coordinates.
console.log(position);
latitude = position.coords.latitude;
longitude = position.coords.longitude;
$("#coordinates").html("latitude: " + latitude + "<br>longitude: " + longitude);
$.ajax(
{
cache: false,
url: "http://api.openweathermap.org/data/2.5/weather?lat=" + latitude + "&lon=" + longitude + "&APPID=a364569e766afcc39428c1a2e3d56ea6&units=metric",
//hand off JSON weather data to success callback function as argument
success: function(result) {
currentWeather = {
id: result.weather[0].id,
condition: result.weather[0].main,
description: result.weather[0].description,
icon: result.weather[0].icon,
temperature: Math.round(result.main.temp),
pressure: result.main.pressure,
humidity: result.main.humidity,
minTemp: result.main.temp_min,
maxTemp: result.main.temp_max,
pressureSea: result.main.sea_level,
pressureGround: result.main.grn_level,
windSpeed: result.wind.speed,
windDegrees: result.wind.deg,
cloudiness: result.clouds.all,
country: result.sys.country,
location: result.name,
sunrise: result.sys.sunrise,
sunset: result.sys.sunset,
symbol: result.weather[0].icon
}
console.log(currentWeather);
//use currentWeather here inside the success function, to manipulate the DOM.
getCountryName(currentWeather.country); //convert country code to full country name
currentWeather.temperatureF = Math.round(currentWeather.temperature * (9/5) + 32) ;
console.log(currentWeather.temperatureF);
$("#location").html(currentWeather.location + ", " + currentWeather.country);
$("#temperature").html(currentWeather.temperature + " &#8451").show();
$("#temperatureF").html(currentWeather.temperatureF + " &#8457").hide();
$("#weatherStatus").html(currentWeather.description);
$('#toggleTemperature').click(function(){
$('#temperature').toggle();
$('#temperatureF').toggle();
})
setWeatherSymbol(currentWeather.symbol);
//serve a random background image based on location. Call a setBackground function with getJSON API to Unsplash. If success there, callback function to set background.
changeImage(currentWeather.country);
}
});
}
setCoordinates(setWeather); //setCoordinates first and callback setWeather with coordinates; that in turn has an AJAX request to get the Weather data and manipulate the DOM
$('#newBackground').on('click', function(){
changeImage(currentWeather.country);
});
});
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
#credits {
font-style: italic;
}
html {
height: 100%;
}
body {
min-height: 100%;
padding-top: 60px;
background-image: url("https://images.unsplash.com/photo-1444044205806-38f3ed106c10?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&w=1080&fit=max&s=cc252deaf87959807785d9afa2022b2f");
background-repeat: no-repeat;
background-size: cover;
font-family: 'Merriweather', serif;
font-style: bold;
color: #2c3e50;
}
#box {
position:relative;
}
.photographer {
position:absolute;
bottom:0;
right:0;
padding-right: 20px;
padding-left: 20px;
padding-bottom: 10px;
color: white;
}
.wi {
font-size: 3em;
}
.well {
opacity: 0.7;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/weather-icons/2.0.9/css/weather-icons.css" rel="stylesheet" />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment