RECENT POST

TOP POST

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

by | Sep 26, 2023

Accurate weather predictions are helping businesses for many purposes today. Weather forecasting data obtained with weather observations has recently become a very valuable resource. We can see accurate weather forecasts in the weather dashboard of almost every website with high user traffic.

Every weather dashboard with accurate weather forecasts is the most effective step in increasing user satisfaction today. It is also one of the simplest steps. Today, businesses and developers can use many accurate forecast provider services. They can use one of these providers to provide accurate forecasts to their users or analyze these data. This article will discuss the importance of accurate weather forecast data and its use cases. Then, we will develop a stunning, accurate weather forecast dashboard.

What is the Importance of Accurate Weather Forecasts?

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

  • Safety: Accurate weather forecasts can directly help keep people and property safe by predicting dangerous weather conditions such as natural disasters. For example, knowing about a rapidly approaching storm or hurricane can help the public take early action, minimizing potentially dangerous situations.
  • Transportation and Travel: Weather forecasts are one of the primary factors influencing trip planning. Accurate forecasts can help travelers plan their flights or road trips and make necessary adjustments based on that data.
  • Agriculture: The agricultural sector is one of the fields of activity that is greatly affected by weather conditions. Accurate weather forecasts can provide farmers with information on which crops to plant or harvest.
  • News and Media: Weather forecasts are information that is often presented in the news. Accurate forecasts keep the public informed of possible weather changes and conditions.
  • Natural Resource Management: Weather forecasting is essential for protecting and managing natural resources such as water management, forest fires, flood control, and environmental management.

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

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.

In addition, this API provides its users with unique documentation. With this documentation, developers and businesses can easily have a lot of information about the API, such as API authentication, HTTPS encryption, and API error codes. Finally, its documentation provides sample integration codes for programming languages such as PHP, Python, and Node.js.

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 open an HTML file in the file path where we will develop the application and put the following codes in this file:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Weather Dashboard</title>
  <style>
    html,
    body {
      font-family: "Abel", sans-serif;
      display: flex;
      align-items: center;
      justify-content: center;
      height: 100%;
    }

    .weather-dashboard {
      padding: 30px 50px;
      border-radius: 6px;
      box-shadow: 0px 2px 20px 5px rgba(0, 0, 0, 0.1);
      background-color: floralwhite;
    }

    .location {
      font-size: 1.8em;
      color: #888;
      position: relative;
      margin-bottom: 5px;
    }

    .weather-data {
      margin: 0;
      padding: 0;
    }

    .weather-data li {
      margin-right: 30px;
      display: inline-block;
    }

    .weather-data li:first-child {
      margin-right: 55px;
    }

    .weather-data li:last-child {
      margin-right: 0;
    }

    .day-name {
      margin-bottom: 11px;
      color: #888;
      display: block;
      font-weight: bold
    }

    .current-temperature {
      font-size: 4em;
      color: #888;
    }

    .forecast-temperature {
      font-size: 1em;
      color: #888;
      margin-bottom: 15px;
    }

    .icons {
      height: 25px;
      width: 25px;
      background-position: center center;
      background-size: 25px;
      background-repeat: no-repeat;
    }

    .weather_description {
      margin-left: 12px;
    }

    .localtime {
      margin-bottom: 40px;
    }
  </style>
</head>
<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>
  <script>
    const apiKey = "YOUR-API-KEY";
    const apiUrl = `https://api.weatherstack.com/forecast?access_key=${apiKey}&query=New York&forecast_days=5&hourly=0`;
    fetch(apiUrl)
      .then(response => response.json())
      .then(jsonResponse => {
        const current = jsonResponse.current;

        // Update HTML elements with API data
        document.getElementById("location").textContent = jsonResponse.location.name;
        document.getElementById("weather-icon").src = current.weather_icons[0];
        document.getElementById("temperature").textContent = `${current.temperature}°C`;

        // Display 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}`;

        // Display weather description
        const weatherDescription = current.weather_descriptions[0];
        document.getElementById("weather_description").textContent = weatherDescription;
        
        const forecast = jsonResponse.forecast;
        // Get today's date in the format "YYYY-MM-DD"
        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(); // Get day index (0-6) for the given date
            const dayName = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"][dayIndex];

            // Create li element
            const li = document.createElement("li");

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

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

            daysList.appendChild(li);
          }
        }
      })
      .catch(error => {
        console.error("Error fetching data:", error);
      });
  </script>
</body>
</html>

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. Before running the application, let’s put our own 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