Home > Web Front-end > JS Tutorial > body text

Building a real-time weather forecast application based on JavaScript

王林
Release: 2023-08-09 15:42:26
Original
1497 people have browsed it

Building a real-time weather forecast application based on JavaScript

Building a real-time weather forecast application based on JavaScript

With the development of technology, weather forecast has become an indispensable part of life. Using JavaScript to build a real-time weather forecast application can easily obtain and display the latest weather information. This article will introduce how to use JavaScript to build a simple real-time weather forecast application, with code examples.

First, we need to get weather data. Weather data can be obtained through interfaces. One of the commonly used and free interfaces is OpenWeatherMap (https://openweathermap.org/). Register on the website and apply for an API key to use its interface to obtain real-time weather data.

The following are the steps to obtain weather data:

  1. Create HTML file
    Create an HTML file named index.html for building the interface of the weather forecast application. Add a div element with the ID "weather-app" and a form element with the ID "search-form" to the body of the HTML file to display weather information and search boxes.
<!DOCTYPE html>
<html>
<head>
  <title>实时天气预报应用</title>
</head>
<body>
  <div id="weather-app">
    <form id="search-form">
      <input type="text" id="search-input" placeholder="输入城市名">
      <button type="submit">搜索</button>
    </form>
    <div id="weather-info"></div>
  </div>

  <script src="app.js"></script>
</body>
</html>
Copy after login
  1. Create JavaScript file
    Create a JavaScript file named app.js in the same directory to process the acquisition and display of weather data.
// 使用fetch方法获取天气数据
function getWeatherData(city) {
  const apiKey = 'YOUR_API_KEY'; // 替换成你的API密钥
  const apiUrl = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}`;

  return fetch(apiUrl)
    .then(response => response.json())
    .then(data => {
      return {
        cityName: data.name,
        weather: data.weather[0].description,
        temperature: data.main.temp
      };
    });
}

// 更新天气信息
function updateWeatherInfo(weatherData) {
  const weatherInfo = document.getElementById('weather-info');
  weatherInfo.innerHTML = `
    <h2>${weatherData.cityName}</h2>
    <p>天气状况:${weatherData.weather}</p>
    <p>温度:${Math.round(weatherData.temperature - 273.15)}℃</p>
  `;
}

// 监听表单提交事件
const searchForm = document.getElementById('search-form');
searchForm.addEventListener('submit', (event) => {
  event.preventDefault();
  const searchInput = document.getElementById('search-input');
  const city = searchInput.value;
  
  // 获取天气数据并更新天气信息
  getWeatherData(city)
    .then(data => updateWeatherInfo(data));
});
Copy after login

Now, you have completed a simple real-time weather forecast application. Users can enter the city name in the search box, and the application will obtain the weather information of the corresponding city and display it on the page.

The above are the steps for building a real-time weather forecast application using JavaScript. By calling the weather interface to obtain data, and using JavaScript to process and display the data, we can easily build a practical weather forecast application. Of course, this is just a simple example, you can extend and beautify the functions and interface of the application according to your own needs.

I hope the above content can help you, and happy programming!

The above is the detailed content of Building a real-time weather forecast application based on JavaScript. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!