user4561451
user4561451

Reputation:

Fetch Weather Data from OpenWeatherMap.org and put in Javascript Value

I have been working over the past week on trying to get to know the OpenWeatherMap API (link) but I am currently having trouble inputting the temperature into a JavaScript variable. I have worked with many tutorials, but I have yet to find one that puts the temperature value into a JavaScript variable.

If you guys are wondering, this is the structure of the API:

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

I currently have this code:

<!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>

Thanks in advance, Ricky

Upvotes: 0

Views: 3010

Answers (1)

user4561451
user4561451

Reputation:

I found a solution using the wunderground API. It is the Weather Network's API. The following is the code that takes a User Input and returns Location, Temperature, Humidity and Wind Speed. Javascript:

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:
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:
<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>

Upvotes: 0

Related Questions