从OpenWeatherMap.org获取天气数据并输入Javascript值

时间:2016-07-15 16:44:02

标签: javascript html json openweathermap

过去一周我一直在努力了解OpenWeatherMap API(link),但我目前无法将温度输入JavaScript变量。我曾经使用过许多教程,但我还没有找到一个将温度值放入JavaScript变量的教程。

如果你们想知道,这是API的结构:

http://api.openweathermap.org/data/2.5/weather?q=London&APPID=YourAPIKEY&units=metric

我目前有这段代码:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>My Weather App</title>
    <script src="weatherapp.js" type="text/javascript"></script>

    <style> body {padding: 0; margin: 0;} canvas {vertical-align: top;} </style>
  </head>
  <body>

    <script>
var weather;

loadJSON ('http://api.openweathermap.org/data/2.5/weather?q=London&APPID=YOURDATA', gotData);

function gotData(data) {
  weather = data;
  window.alert(weather.main.temperature);
}

</script>
  </body>
</html>

提前致谢, 瑞奇

1 个答案:

答案 0 :(得分:0)

我找到了使用wunderground API的解决方案。这是天气网络的API。以下是采用用户输入并返回位置,温度,湿度和风速的代码。 使用Javascript:

&#13;
&#13;
var weather = new XMLHttpRequest();
var city = "London";
var prov = "GB";
function testFunction (){
  var city = document.getElementById("city").value;
  var prov = document.getElementById("state").value;
  weather.open("GET", "http://api.wunderground.com/api/YOURAPIID/conditions/q/" + prov + "/" + city + ".json", false);
  weather.send(null);
  var r = JSON.parse(weather.response);

  var dis = "Current location: " + r.current_observation.display_location.full + "  <p>";
  var temp = r.current_observation.temp_c + "  <p>";
  var wind = r.current_observation.wind_string + "  <p>";
  var humid = r.current_observation.relative_humidity +"   <p>";
  function getWeather(id, res) {
    document.getElementById(id).innerHTML = res;
  }

  getWeather("weather", dis);
  getWeather("temp", temp);
  getWeather("wind", wind);
  getWeather("humid", humid);
 //alert ('gey')
}
  
CSS:
&#13;
body {
  font-family: sans-serif;
  width: 800px;
  font-size: 3em;
  margin: auto;
}

#weather {
  margin-top: 100px;
}

#temp {
  font-weight: bold;
}

#temp:hover {
  background: yellow;
  cursor: pointer;
}

#wind {
  font-style: italic;
}
HTML:
&#13;
<div id="weather"></div>
<p>Current Temp: <span id="temp"></span></p>
<p>Current Wind: <span id="wind"></span></p>
<p>Current Humidity: <span id="humid"></span></p>
City: <input id="city" value="London"></input><br>
Province/Country: <input id="state" value="GB"></input>
<button onclick="testFunction()">Submit</button>
&#13;
&#13;
&#13;