Weather App using API

Why? Learn fetch() API and working with JSON.

<!DOCTYPE html>
<html>
<head>
  <title>Weather App</title>
</head>
<body>
  <h2>🌦 Weather App</h2>
  <input type="text" id="city" placeholder="Enter city">
  <button onclick="getWeather()">Search</button>
  <p id="result"></p>

  <script>
async function getWeather() {
  let city = document.getElementById("city").value;
  let apiKey = "your_api_key"; // get free key from openweathermap.org
  let url = https://api.openweathermap.org/data/2.5/weather?q=${city}&amp;amp;appid=${apiKey}&amp;amp;units=metric;
  let response = await fetch(url);
  let data = await response.json();
  if (data.cod === "404") {
    document.getElementById("result").innerText = "City not found!";
  } else {
    document.getElementById("result").innerText =
      `šŸŒ ${data.name}, ${data.sys.country}  
      🌔 Temp: ${data.main.temp}°C  
      ☁ Weather: ${data.weather&#91;0].description}`;
  }
}
</script> </body> </html>

Explanation:

  • User enters a city name.
  • fetch() calls OpenWeatherMap API.
  • JSON data is parsed and displayed.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *