Skip to content

Instantly share code, notes, and snippets.

@sarkistlt
Created May 7, 2016 21:57
Show Gist options
  • Save sarkistlt/e6458aa7c700cf6ebbc0166e61b15137 to your computer and use it in GitHub Desktop.
Save sarkistlt/e6458aa7c700cf6ebbc0166e61b15137 to your computer and use it in GitHub Desktop.
native javaScript ES6. just insert this file in any HTML and js will do rest of work.
let XHR = (`onload` in new XMLHttpRequest()) ? XMLHttpRequest : XDomainRequest; //to support IE8
let ipXhr = new XHR(),
weatherXhr = new XHR();
let creatElement = function () {
let layoutBody = document.createElement('div'),
h1 = document.createElement('h1'),
p = document.createElement('p'),
img = document.createElement('img'),
h2 = document.createElement('h2');
layoutBody.id = "layout__body";
h1.id = "city";
p.id = "temp";
img.id = "icon";
h2.id = "description";
layoutBody.appendChild(h1);
layoutBody.appendChild(p);
layoutBody.appendChild(img);
layoutBody.appendChild(h2);
document.body.appendChild(layoutBody);
}();
ipXhr.open(`GET`, `https://weathersync.herokuapp.com/ip`, true);
ipXhr.send();
ipXhr.onreadystatechange = function () {
let lat = ``,
lng = ``;
if (ipXhr.readyState != 4) return;
if (ipXhr.status != 200) {
console.log(`error ${ipXhr.status}: ${ipXhr.statusText}`);
} else {
let ip = JSON.parse(ipXhr.responseText);
lat = ip.location.latitude;
lng = ip.location.longitude;
weatherXhr.open(`GET`, `https://weathersync.herokuapp.com/weather/${lat},${lng}`, true);
weatherXhr.send();
weatherXhr.onreadystatechange = function () {
if (weatherXhr.readyState != 4) return;
if (weatherXhr.status != 200) {
console.log(`error ${weatherXhr.status}: ${weatherXhr.statusText}`);
} else {
let obj = JSON.parse(weatherXhr.responseText),
city = obj.name,
temp = Math.floor(1.8 * (obj.main.temp - 273) + 32), //Convert Kelvin to Fahrenheit
icon = `http://openweathermap.org/img/w/${obj.weather[0].icon}.png`,
description = obj.weather[0].description;
document.getElementById(`city`).innerHTML = city;
document.getElementById(`temp`).innerHTML = `${temp} ºF`;
document.getElementById(`icon`).src = icon;
document.getElementById(`description`).innerHTML = description;
}
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment