RECENT POST

TOP POST

Show Weather Forecast Data Based on Users’ Location

by | Aug 16, 2023

Weather conditions affect almost everyone, from businesses to individuals, in one way or another. For instance, weather conditions greatly impact what clothes we wear, the activities we can do, etc. They 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 as well as 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 like weatherstack that is known to provide accurate and consistent data. 

In this article, we’ll show you how to create a simple web page 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!

How Does An IP Geolocation API Work?

How Does An IP Geolocation API Work?

An IP geolocation API uses the IP address of the electronic device your website visitor uses to access your website and determine the user’s location based on the IP address. An IP address is essentially an internet protocol address. It is a unique address or number assigned to each electronic device, such as a laptop, smartphone, or tablet, connected to the internet of a private network. It is a string of decimal-separated numbers and is basically used to identify the devices on the internet. An example of an IP address is 192.121.3. There are different types of IP addresses, such as private IP addresses, static IP addresses, and public IP addresses. An IP geolocation API usually returns country, region, state, city, latitude, and longitude. 

A reliable IP geolocation API usually gathers data from dependable sources, such as:

Regional Internet Registries (RIRs)

RIRs are essentially the organizations that are responsible for the distribution of Internet number resources, including IP addresses from various regions across the globe.

Internet Service Providers (ISPs)

Some ISPs allow sharing of IP address data. A reliable IP geolocation API gathers this data to improve geolocation data accuracy.

Data Submitted By Users

Some IP geolocation APIs also utilize the location data provided by the users while submitting website forms or when users enable access to their location while using a web browser.

Why Use 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.

Ipstack offers a range of features and endpoints that make it one of the most trusted IP-to- geolocation APIs:

Highly Accurate and Detailed Data

Ipstack is undoubtedly one of the most accurate IP geolocations APIs available in the market. The API sources data from large, dependable ISPs (Internet Service Providers) to deliver accurate and consistent data. Moreover, the API returns detailed location information, such as continent, country, city, region, latitude, and longitude. The API also has a Connection Module that provides information regarding the hostname and ASN of the ISP your website users use.

Supports IPv4 and IPv6 Address

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.

Bulk Lookup

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.

Currency Module

ipstack currency module

Depending on your subscription plan, you can use ipstack’s currency module to request currency data of the location returned against the given IP address. This feature provides accurate currency data and returns the currency’s symbol, name and code. You can use this data to display the prices of products in the local currencies of users to deliver a personalized shopping experience.

Security Module

As cyber-attacks are increasing day by day, website security has become more important than ever. With ipstack’s security module, you can 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.

Time Zone Module

Ipstack is also capable of providing the time zone information of the location returned against a given IP address. This data includes the GMT offset, current time, and code. This information helps optimize your marketing campaign.

Easy to Implement

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.

Why Use Weatherstack API?

weatherstack Weather API home page

Weatherstack is a widely-used weather data API that provides highly accurate, real-time and historical global weather data. From Microsoft and Deloitte to Schneider and Ericsson, thousands of large organizations, SMBs, and developers use weatherstack. 

Here are the key features of the API:

Real-Time Weather Data

Weatherstack returns accurate real-time weather data of any location worldwide. You can request real-time data by attaching any location of your choice to the API’s “current” endpoint. You can also request weather data for multiple locations simultaneously by separating the locations using a semicolon. The API returns detailed weather data, including temperature, weather description, wind speed, pressure, visibility, wind degree, etc. 

Historical Weather Data

With weatherstack, you can request weather data all the way back year 2008. You just need to provide any data of your choice and use the historical endpoint. You can also request data for multiple dates simultaneously. Additionally, the API can provide historical time-series data using the start and end date of your choice. The historical data is useful in understanding weather trends and patterns.

Weather Forecast Data

Weatherstack also provides highly accurate weather forecast data for up to 14 days into the future. You can request this data using the API’s forecast endpoint and specify your preferred number of days. You can also enable hour-by-hour updates, depending on your subscription plan. The API provides detailed information for each day, including minimum and maximum temperatures, humidity, etc.

How to Show Weather Forecast Data Based on Users’ Location?

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. Here, we’ll demonstrate how to use 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 use this location data and show weather forecast data of the location on our web page. 

Before you start using the APIs, you need to get your ipstack and weatherstack API keys. You can get your free ipstack API key by signing up. Weatherstack also offers a free plan, but it only supports real-time data. You need to subscribe to the Professional or Business plan for weather forecast data. 

ipstack CTA banner - Locate and Identify Visitors by IP address - sign up

Here is the 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>
          `;

You must insert your API key instead of ‘YOUR_ipstack_ACCESS_KEY’ in the above code.

CTA - Weatherstack Weather Forecast Data and Historical Weather Data API - Sign Up Free

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

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 temperate and maximum temperate, but you can also display other weather parameters supported by weatherstack, such as humidity, description, etc.

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.

When you open the above HTML page in your web browser, it’ll show the following output:

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?

Frequently Asked Questions (FAQs)

What are the data sources of weather forecast APIs?

A reliable weather forecast API like weatherstack sources data from various dependable sources like personal weather stations, large weather stations, and satellite imagery.

How can I download weather forecast data for my weather app?

You can use an efficient weather API like weatherstack to fetch and display accurate weather forecast data on your web app.

Which weather API is the most accurate?

Weatherstack is one of the most trusted weather data APIs. It provides highly accurate real-time, historical, and weather forecast data. 

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