-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathweather_api_demo.html
72 lines (63 loc) · 2.72 KB
/
weather_api_demo.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<!DOCTYPE html>
<html>
<head>
<title>Parsing OpenMapAPI using JavaScript Object Notation</title>
<script>
var txt = "", desc = "";
var myXMLHttpRequest = new XMLHttpRequest();
//var url = "http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139" ;
var url = "http://api.openweathermap.org/data/2.5/forecast?id=1253184&APPID=bf37e0bdc8114a593035938165a47fcf";
myXMLHttpRequest.onreadystatechange = function() {
if (myXMLHttpRequest.readyState === 4 && myXMLHttpRequest.status === 200)
{
// the JSON response deserialized
var myObject = JSON.parse(myXMLHttpRequest.responseText);
//for (i in myObject.list.dt.weather) {
//x += "<h2>" + myObject.list.dt.weather[i].description + "</h2>";
//}
// let's display the weather on the page
var description = "My city id is " + myObject.city.id + " My city name is " + myObject.city.name + "Coordinates of the city:" + "lat is"+myObject.city.coord.lat + "long is" + myObject.city.coord.lon;
//var description = "My city id is " + myObject.city.id + " My city name is " + myObject.city.name + "Coordinates of the city:" + "lat is"+myObject.city.coord.lat + "long is" + myObject.city.coord.lon;
document.getElementById("weather").innerHTML = description;
txt += "<table border='1'>";
for (x in myObject.list)
{
//txt += "<tr><td>" + myObject.list[x].clouds.all + "</td></tr>";
txt += "<tr><td>" + myObject.list[x].main.temp + "</td></tr>";
}
txt += "</table>"
//desc += "</table>"
document.getElementById("demo").innerHTML = txt;
// The object serialized
var myJSON = JSON.stringify(myObject);
// let's display this in the div with the id "json"
document.getElementById("json").innerHTML = myJSON;
}
else if (myXMLHttpRequest.readyState === 4 && myXMLHttpRequest.status !== 200)
{
// fail.
document.getElementById("weather").innerHTML = "failed.";
document.getElementById("json").innerHTML = "failed.";
document.getElementById("error").innerHTML = "Unable to connect to the open weather map API. Are you connected to the internet? Is <a href='http://api.openweathermap.org/data/2.5/forecast?id=1253184&APPID=bf37e0bdc8114a593035938165a47fcf'>this page</a> responsing? If it's not, try again later."
}
}
myXMLHttpRequest.open("GET", url, true);
myXMLHttpRequest.send();
</script>
</head>
<body>
<h1>JavaScript Object Notation Demo using Weather data</h1>
<h2>The Weather</h2>
<div id="weather">
loading...
</div>
<h2>The JSON as a String</h2>
<div id="json">
loading...
</div>
<div id="error">
</div>
<div id="demo">loading...
</div>
</body>
</html>