RECENT POST

TOP POST

Present Users’ Location-Based Weather Forecast Data

by | Aug 22, 2024

Weather conditions affect almost everyone, from businesses to individuals, in one way or another. They greatly impact what clothes we wear, the activities we can do, etc. Weather conditions also affect businesses such as retail, event management, construction, etc. Take, for example, the retail industry, where the demand, production and delivery of certain items vary with the change in weather conditions. Hence, businesses and individuals often need weather forecast data and current weather data. As a result, the use of weather apps is increasing day by day. While a handful of weather apps are available today, not all of them show accurate data. 

If you’re a developer looking to create a weather app that stands out from the crowd, it’s crucial to ensure your app shows highly accurate data. To create such an app, you need to use a reliable weather API that is known to provide accurate and consistent data. 

In this article, we’ll show you how to create a simple web app that uses an IP geolocation API to automatically determine the location of the website visitors based on their IP address. We’ll then use this location to show weather forecast data to users. 

Here, we’ll be using ipstack IP geolocation API and weatherstack weather API. Both APIs are known for their accuracy, high speed, consistency, and reliability. Let’s get started!

Getting Location Data of Users

To create a weather app that automatically shows weather forecast data based on the user’s location, we first need to implement some sort of mechanism to determine the user’s location. The best way to do this is to use an IP geolocation API. 

An illustration of IP geolocation

An IP geolocation API automatically determines the location of a website visitor based on the IP address of the electronic device they use to visit the website. An IP address is essentially a unique address assigned to every internet-connected electronic device. This can be a laptop, smartphone,  tablet or a desktop PC. 

The location data provided by an IP geolocation API usually include:

  • Country
  • City
  • Region
  • Latitude and longitude

Introducing Ipstack API

ipstack ip geolocation api home page

Ipstack is a leading IP geolocation API that delivers highly accurate, real-time location data of your website visitors based on their device’s IP address. The high-performance API is scalable and can process thousands of requests without compromising performance. Moreover, The API is highly secure. 

It uses 256-bit SSL encryption/HTTPS to ensure all the data sent to and processed by the API is secure. Thousands of developers, SMBs and enterprises, including Samsung, Mircosoft, Airbnb and Hubspot, trust ipstack due to its impressive features, high performance, security, and ease of use.

Here are the key reasons why we chose ipstack:

  • Ipstack is widely recognized for its high accuracy. The API sources data from large, dependable ISPs (Internet Service Providers) to deliver accurate and consistent data. 
  • The API returns detailed location information, such as continent, country, city, region, latitude, and longitude. 
  • Ipstack supports both IPv4 and IPv6 addresses and covers over 2 million unique locations in 200,000+ cities across the world. Hence, the API can provide accurate location data of any user accessing your website from any location.
  • With ipstack’s bulk lookup, you can request location data of multiple IP addresses (up to 50) simultaneously. This way, you don’t have to request data for each IP address separately.
  • Ipstack offers a security module that helps you protect your website from cyber-attacks. This module essentially allows you to examine security threats and risks associated with a suspicious IP address. You can then block such IP addresses to protect your site.
  • The API is super easy to integrate and has detailed documentation that provides all the details about the API methods, features, parameters and endpoints. It also provides several coding examples to help you get started quickly and simplify API integration.

Selecting a Weather API

We’ll need to use a reliable weather API in our app to fetch weather forecast data for the user’s location detected by the IP geolocation API. While there are various weather APIs in the market, not all of them are made equal. 

When choosing a weather API, the accuracy of data is the most important factor to consider. That’s because inaccurate data significantly affects the user experience. 

For this reason, we chose weatherstack API for our app. Weatherstack is a widely-used weather data API known for its high accuracy for real-time data, weather forecasts, and historical global weather data. Thousands of developers, SMBs, and large organizations leverage weatherstack, including Microsoft and Deloitte to Schneider and Ericsson.

weatherstack Weather API home page

Here are the key features of weatherstack API:

  • Weatherstack returns highly accurate real-time weather data of any location worldwide. You can also request weather data for multiple locations simultaneously.
  • The API returns detailed weather data, including temperature, weather description, wind data, pressure, visibility, wind degree, etc. 
  • With weatherstack, you can request historical weather data all the way back year 2008. The API also supports historical time-series data. This data is useful in understanding weather trends and patterns.
  • Weatherstack is widely recognized for its highly accurate weather forecast data. The weather forecast API supports weather forecasts for up to 14 days into the future. You can also enable hour-by-hour updates, depending on your subscription plan. The API provides detailed climate data for each day, including minimum and maximum temperatures, humidity, etc.

Displaying Weather Forecast Data Based on Users’ Location: Coding Examples

World Weather Map

Here, we’ll create a simple web page using HTML, CSS, and JavaScript that will determine the users’ location using the ipstack API and then use this location data to show weather data to users. 

We’ll be using ipstack’s Requester IP Lookup to determine the IP address from which the current API request is coming. Then, we’ll use this IP address along with the ipstack’s standard lookup to determine the user’s location (city, country, region, latitude, and longitude). You can also retrieve location data directly from the Requester Lookup endpoint. 

Finally, we’ll show weather forecast data on our app based on the location detected by the ipstack IP Geolocation API. 

Note: To use these APIs, you need to get your API keys. You can get your free ipstack and weatherstack API keys by signing up with the respective platform. While weatherstack offers a free plan, it only supports real-time data. You need to subscribe to the Professional or Business plan to get weather forecast data. 

Retrieving Location Data of Users

Here is an example code for fetching location data from ipstack:

const ipstackAccessKey = 'YOUR_ipstack_ACCESS_KEY';

fetch(`http://api.ipstack.com/check?access_key=${ipstackAccessKey}`)

    .then(response => response.json())

    .then(data => {

      const ipAddress = data.ip;

      fetch(`http://api.ipstack.com/${ipAddress}?access_key=${ipstackAccessKey}`)

        .then(response => response.json())

        .then(locationData => {

          const locationElement = document.getElementById('location');

          const city = locationData.city;

          const region = locationData.region_name;

          const country = locationData.country_name;

          const latitude = locationData.latitude;

          const longitude = locationData.longitude;


          locationElement.innerHTML = `Your location: ${city}, ${region}, ${country}`;
          const locationRow = document.getElementById('locationRow');

          locationRow.innerHTML = `

            <td>${city}</td>

            <td>${region}</td>

            <td>${country}</td>

            <td>${latitude}</td>

            <td>${longitude}</td>

          `;

Remember to insert your actual API key instead of ‘YOUR_ipstack_ACCESS_KEY’ in the above code.

Displaying Weather Forecast Data Based on the Detected User’s Location

Here is an example code for fetching 3-day weather forecast data from the weatherstack API using the city data we extracted in the previous section.

const weatherstackAccessKey = 'YOUR_Weatherstack_ACCESS_KEY'

const weatherApiUrl = `http://api.weatherstack.com/forecast?access_key=${weatherstackAccessKey}&query=${city}&forecast_days=3`;


          fetch(weatherApiUrl)

            .then(response => response.json())

            .then(weatherData => {

              console.log('Weather Data Response:', weatherData);


              const forecastTableBody = document.getElementById('forecastTableBody');

              forecastTableBody.innerHTML = '';


              for (const date in weatherData.forecast) {

    if (weatherData.forecast.hasOwnProperty(date)) {

      const forecast = weatherData.forecast[date];

      const minTemp = forecast.mintemp;

      const maxTemp = forecast.maxtemp;


      forecastTableBody.innerHTML += `

        <tr>

          <td>${date}</td>

          <td>${minTemp}°C</td>

          <td>${maxTemp}°C</td>

        </tr>

              `;

    }

}
})

We’ll display the date, minimum and maximum temperate, but you can also display other weather parameters supported by weatherstack, such as humidity, description, etc.

Complete Code for the Weather App

Here is the complete HTML, CSS, and JS code:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Weather App</title>

<style>

  body {

    font-family: Arial, sans-serif;

    display: flex;

    justify-content: center;

    align-items: center;

    min-height: 100vh;

    margin: 0;

    background-color: #f0f0f0;

  }

  #content {

    background-color: white;

    padding: 20px;

    border-radius: 10px;

    box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);

    text-align: center;

  }

  table {

    width: 100%;

    border-collapse: collapse;

    margin-top: 20px;

  }

  th, td {

    padding: 10px;

    border-bottom: 1px solid #ddd;

  }

  th {

    background-color: #f2f2f2;

  }

  #weather {

    margin-top: 20px;

    font-weight: bold;

  }

</style>

</head>

<body>

<div id="content">

  <h1>Weather App</h1>

  <div id="location"></div>

  <table>

    <caption>Location Data</caption>

    <tr>

      <th>City</th>

      <th>Region</th>

      <th>Country</th>

      <th>Latitude</th>

      <th>Longitude</th>

    </tr>

    <tr id="locationRow">

      <td></td>

      <td></td>

      <td></td>

      <td></td>

      <td></td>

    </tr>

  </table>

  <table>

    <caption>Weather Forecast (Next 3 Days)</caption>

    <thead>

      <tr>

        <th>Date</th>

        <th>Min Temp (°C)</th>

        <th>Max Temp (°C)</th>

      </tr>

    </thead>

    <tbody id="forecastTableBody"></tbody>

  </table>

</div>


<script>

  const ipstackAccessKey = 'YOUR_ipstack_ACCESS_KEY';

  const weatherstackAccessKey = 'YOUR_Weatherstack_ACCESS_KEY';


  fetch(`http://api.ipstack.com/check?access_key=${ipstackAccessKey}`)

    .then(response => response.json())

    .then(data => {

      const ipAddress = data.ip;


      fetch(`http://api.ipstack.com/${ipAddress}?access_key=${ipstackAccessKey}`)

        .then(response => response.json())

        .then(locationData => {

          const locationElement = document.getElementById('location');

          const city = locationData.city;

          const region = locationData.region_name;

          const country = locationData.country_name;

          const latitude = locationData.latitude;

          const longitude = locationData.longitude;


          locationElement.innerHTML = `Your location: ${city}, ${region}, ${country}`;


          const locationRow = document.getElementById('locationRow');

          locationRow.innerHTML = `

            <td>${city}</td>

            <td>${region}</td>

            <td>${country}</td>

            <td>${latitude}</td>

            <td>${longitude}</td>

          `;


          const weatherApiUrl = `http://api.weatherstack.com/forecast?access_key=${weatherstackAccessKey}&query=${city}&forecast_days=3`;


          fetch(weatherApiUrl)

            .then(response => response.json())

            .then(weatherData => {

              console.log('Weather Data Response:', weatherData);


              const forecastTableBody = document.getElementById('forecastTableBody');

              forecastTableBody.innerHTML = '';


              for (const date in weatherData.forecast) {

    if (weatherData.forecast.hasOwnProperty(date)) {

      const forecast = weatherData.forecast[date];

      const minTemp = forecast.mintemp;

      const maxTemp = forecast.maxtemp;


      forecastTableBody.innerHTML += `

        <tr>

          <td>${date}</td>

          <td>${minTemp}°C</td>

          <td>${maxTemp}°C</td>

        </tr>

              `;

    }

}

            })

            .catch(error => {

              console.error('Error fetching weather data:', error);

              const forecastTableBody = document.getElementById('forecastTableBody');

              forecastTableBody.innerHTML = '<tr><td colspan="3">Weather forecast data not available.</td></tr>';

            });

        })

        .catch(error => {

          console.error('Error fetching location data:', error);

          const locationElement = document.getElementById('location');

          locationElement.innerHTML = 'Error fetching location data.';

        });

    })

    .catch(error => {

      console.error('Error fetching IP address data:', error);

      const locationElement = document.getElementById('location');

      locationElement.innerHTML = 'Error fetching IP address data.';

    });

</script>

</body>

</html>

Don’t forget to replace ‘YOUR_ipstack_ACCESS_KEY’ and ‘YOUR_Weatherstack_ACCESS_KEY’ with your unique API keys.

Output

When you open the above HTML page in your web browser, it’ll show the following output (weather data by location):

Weather forecast data retrived using the weathetstack API

Note: The location and weather forecast data will change depending on the location the user accesses your website from.

Also Read: How to create a weather forecasting chatbot?

Conclusion

In this tutorial, we’ve created a simple weather app that shows weather forecast data based on the user’s location. We’ve used ipstack IP geolocation API to accurately determine the location of the user based on the IP address of the electronic device they use to visit the weather app. 

Then, based on this detected location, we’ve displayed 3-day weather forecast data by leveraging weatherstack API.

Sign up for weatherstack for free today to get real-time data, or subscribe to a paid plan to get reliable weather forecast data!

Frequently Asked Questions (FAQs)

What is the data type for weather forecast?

Weather forecast data can include various parameters, such as:

  • Temperature
  • Humidity
  • Precipitation
  • Wind speed
  • Pressure.

What data is used to predict the weather?

Various sources are used to get weather forecast data, . These include satellite imagery, radar data, weather station data, and more.

What are the sources of data for weather forecasts?

Primary sources of weather forecast data include:

  • Satellites
  • Weather radars
  • Weather stations
  • Weather buoys

What data goes into a weather forecast?

A weather forecast consists of a wide range of data. This data includes temperature, humidity, precipitation, wind speed and direction, atmospheric pressure, and more. They are collected from different sources, such as weather stations, satellites, and radars. Then, meteorologists use this data, computer models, and historical weather patterns to forecast future weather conditions.