RECENT POST

TOP POST

How to Create a Great Weather Dashboard With a Weather API – Part 3 (Weather Forecast)

by | Jul 16, 2024

Today, accurate weather forecasts are very important for businesses to optimize their operations and make strategic decisions. Detailed and precise forecast data obtained through weather observations has become an indispensable resource in many different areas, from the agricultural sector to the logistics and transportation sectors. This valuable information is used in a wide range of applications, from product planning to event management, from shipping scheduling to energy consumption forecasting. Nowadays, almost every website with high user traffic has a comprehensive weather dashboard that provides weather forecasts that affect users’ daily lives and business processes. These dashboards are usually powered by a weather API.

Today, one of the most effective ways to increase user satisfaction is to provide a dashboard with accurate weather forecasts. This step stands out as both a simple and effective solution. Businesses and developers can use many reliable forecast provider services to provide their users with the most accurate forecasts or to analyze this data. In this article, we will take a detailed look at the importance of accurate weather forecast data and different use cases. We will also cover in detail the steps to developing an impressive and accurate weather dashboard with a weather API, and focus on best practices and techniques.

What is the Importance of Accurate Weather Forecasts?

Accurate weather forecasts are of great importance in many industries and even in our daily lives today. Here are some reasons why accurate weather forecasts are important:

  • Transportation and Travel: Weather forecasts are one of the key factors that play a major role in travel planning. Accurate and timely forecasts allow travelers to plan their flights or trips effectively. These forecasts not only help you know in advance about flight delays or cancellations at the airport but also help you prepare for adverse weather conditions that may occur during your trip. Weather events, such as heavy snowfall in the winter or severe storms in the summer, can greatly affect your travel plans.
  • Agriculture: The agricultural sector is one of the most important areas of activity directly affected by weather conditions. The accuracy of weather forecasts plays a critical role for farmers and helps them plan their agricultural activities. For example, accurate forecasts can help farmers better determine when to plant and when to harvest, thus maximizing crop yields.
  • News and Media: In the world of news and media, weather forecasts are often among the most important pieces of information presented to viewers. Accurate and up-to-date forecasts inform the public about possible weather changes and the conditions these changes will bring. For example, information such as wind speed, humidity, temperature, and pressure forecasts for a city help individuals make daily plans and also enable emergency preparations.
  • Natural Resource Management: Weather forecasting plays a vital role in the conservation and management of natural resources. Accurate and timely weather forecasts are needed in critical areas such as water management, forest fire prevention, flood control, and general environmental management. Correct management of water reserves, especially during drought periods, can be possible by taking precautions in advance based on forecasts.

Create a Stunning, Accurate Weather forecast Dashboard in a Web App

In this part, we will develop a stunning weather forecast dashboard with HTML, CSS, and JavaScript. The data in this dashboard will be obtained from the weatherstack API.

Discover the 5 examples of successful free weather APIs.

The weatherstack API is a very powerful weather forecast API that provides highly accurate weather forecast data for the next 14 days from today for millions of locations. It is the most accurate forecast provider in the market. This API can provide the weather forecast both hourly and daily. It is actively used by 75,000 companies today. Many weather apps get weather data from the weatherstack API.

Also, this API provides its users with comprehensive and unique documentation. This documentation explains all the features and usage details of the API in an understandable way for developers and businesses. Developers can easily access the necessary information on critical topics such as API authentication, HTTPS encryption, and API error codes. The documentation explains step by step how to use the API, and also provides guidance on possible errors and how to resolve them.

Before we integrate the weatherstack API into the web application and start using it, let’s sign up for one of the ‘Professional’ or ‘Business’ subscription plans and get an API key.

After obtaining the API key, Let’s examine the code of the weather forecast dashboard application step by step.

Head Section

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Weather Dashboard</title>
  <style>
    /* CSS styles */
  </style>
</head>

With the head section, we set meta information such as the character encoding, display settings, and page title of our application. At the same time, we will define the appearance and layout of the page by creating CSS styles.

Body Section

<body>
  <div class="weather-dashboard">
    <div id="location" class="location"></div>
    <div id="localtime" class="localtime"></div>
    <ul class="weather-data" id="weather-data-list">
      <li>
        <img id="weather-icon" class="icons">
          <span id="weather_description" class="weather_description"></span>
        </img>
        <div id="temperature" class="current-temperature"></div>
      </li>
    </ul>
  </div>
</body>
</html>

The body section contains the main content of the page. Inside a ‘<div>’ with the ‘weather-dashboard’ class are the HTML elements needed to display the location name, local time, and weather data. These elements are dynamically updated by JavaScript.

Learn how to show weather forecast data based on users’ location!

API Key and URL

const apiKey = "YOUR-API-KEY";
const apiUrl = `https://api.weatherstack.com/forecast?access_key=${apiKey}&query=New York&forecast_days=5&hourly=0`;

This section defines the API key and constructs the API URL for fetching weather data for New York.

Fetching Data

fetch(apiUrl)
  .then(response => response.json())
  .then(jsonResponse => {

The fetch function sends a request to the weather API and processes the response as JSON.

Updating HTML Elements

const current = jsonResponse.current;
document.getElementById("location").textContent = jsonResponse.location.name;
document.getElementById("weather-icon").src = current.weather_icons[0];
document.getElementById("temperature").textContent = `${current.temperature}°C`;

This part extracts current weather data and updates the corresponding HTML elements with the location name, weather icon, and temperature.

Displaying Local Time and Date

const localTime = new Date(jsonResponse.location.localtime);
const dayOfWeek = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"][localTime.getDay()];
const formattedTime = localTime.toLocaleTimeString('en-US', { hour: 'numeric', minute: 'numeric' });
document.getElementById("localtime").textContent = `${dayOfWeek}, ${formattedTime}`;

This code gets the local time from the API response, formats it, and updates the corresponding HTML element.

Displaying Weather Description

const weatherDescription = current.weather_descriptions[0];
document.getElementById("weather_description").textContent = weatherDescription;

This updates the HTML element with the weather description.

Displaying Forecast Data

const forecast = jsonResponse.forecast;
const todayDate = new Date().toISOString().split("T")[0];
const daysList = document.getElementById("weather-data-list");

for (const date in forecast) {
  if (date !== todayDate) {
    const avgTemp = forecast[date].avgtemp;
    const dayIndex = new Date(date).getDay();
    const dayName = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"][dayIndex];

    const li = document.createElement("li");
    const dayNameSpan = document.createElement("span");
    dayNameSpan.classList.add("day-name");
    dayNameSpan.textContent = dayName;
    li.appendChild(dayNameSpan);

    const tempetureDiv = document.createElement("div");
    tempetureDiv.classList.add("forecast-temperature");
    tempetureDiv.textContent = `${avgTemp}°C`;
    li.appendChild(tempetureDiv);

    daysList.appendChild(li);
  }
}

This section loops through the forecast data, creates new list items for each day (excluding today), and updates the HTML with the forecast temperature and day name.

With this application, we created a weather dashboard using the future 4-day weather forecast data and current weather data of the New York location. Moreover, you can access the application code from GitHub.

Before running the application, let’s put our API key in the ‘YOUR-API-KEY’ field and run the application. The weather forecast dashboard we see after running the application is as follows:

accurate weather forecasts dashboard

Conclusion

As a result, creating an impressive weather forecast dashboard using a weather API provides an interactive and informative experience that allows users to easily keep track of current weather conditions. Today, processing and visually presenting data from a weather API has become the more common way to understand weather forecasts. This type of dashboard can make life easier and safer by providing useful information in many areas, from travel planning to choosing daily wear.

Sign up for the best weather forecast API in 2023!

FAQs

Q: What is the Most Accurate Weather Forecast API in the Market?

A: There are many accurate weather forecast APIs on the market. The most popular is the weatherstack API, a weather API preferred by global companies such as Microsoft and Ericsson.

Q: What are the Use Cases of Weather Forecasts?

A: It is frequently used in many fields, such as weather forecasting, travel planning, agricultural management, energy production, daily life decisions, and natural disasters.

Q: Why Is Weather Forecast Accuracy Important?

A: Weather forecast accuracy can impact many critical areas, such as people’s safety, agricultural production, energy planning, and traffic management. Accurate forecasts are important to minimize adverse effects.

Q: Does the weatherstack API Offer Weather Forecasts for Free?

A: No, it does not. This API provides weather forecast data with at least a ‘Professional’ plan.

Read: How to Create a Great Weather Dashboard With a Weather API – Part 1 (Current Weather)

Read: How to Create a Great Weather Dashboard With a Weather API – Part 2 (Historical Weather)

Read: How to Create a Great Weather Dashboard With a Weather API – Part 4 (Current, History, Forecast)

CTA - APILayer API Marketplace - Sign-Up Free