logo
Published on

Local Weather Forecast in SPFx

This article shows how to build a Local Weather Forecast web part in the SharePoint Framework (SPFx) using the OpenWeather API.
It automatically detects the user’s location based on IP address and displays the live weather information.


🌍 Overview

The web part uses two public APIs:

  1. ipinfo.io — to fetch location details (city, region, country, latitude, longitude).
  2. OpenWeatherMap — to retrieve live weather information based on coordinates.

⚙️ Install Required Dependencies

npm install @pnp/sp --save

This installs PnP JS, which you can use for any SharePoint operations (optional for this demo).


🧩 Define the Weather State

Create a file named ISpfxWeatherState.ts under your components folder:

export interface ISpfxWeatherState {
  skyimage: string;
  location: string;
  weatherid: string;
  temperature: string;
  windspeed: string;
  humidity: string;
}

This defines the weather data we’ll store in the component state.


⚛️ Implement the Weather Component

Create SpfxWeather.tsx inside components/ folder.

import * as React from 'react';
import styles from './SpfxWeather.module.scss';
import { ISpfxWeatherProps } from './ISpfxWeatherProps';
import { ISpfxWeatherState } from './ISpfxWeatherState';
import { autobind } from 'office-ui-fabric-react/lib/Utilities';

export default class SpfxWeather extends React.Component<ISpfxWeatherProps, ISpfxWeatherState> {
  constructor(props: ISpfxWeatherProps) {
    super(props);
    this.state = {
      skyimage: '',
      location: '',
      weatherid: '',
      temperature: '',
      windspeed: '',
      humidity: ''
    };
  }

  public render(): React.ReactElement<ISpfxWeatherProps> {
    return (
      <div className={styles.spfxWeather}>
        <h2>Local Weather Forecast</h2>
        {this.state.location && (
          <div>
            <img src={this.state.skyimage} alt="Weather" />
            <p><strong>Location:</strong> {this.state.location}</p>
            <p><strong>Sky:</strong> {this.state.weatherid}</p>
            <p><strong>Temperature:</strong> {this.state.temperature}°C</p>
            <p><strong>Wind Speed:</strong> {this.state.windspeed}</p>
            <p><strong>Humidity:</strong> {this.state.humidity}%</p>
          </div>
        )}
      </div>
    );
  }

  public componentDidMount(): void {
    this.getWeather();
  }

  @autobind
  private async getWeather(): Promise<void> {
    // Step 1: Get user's location based on IP
    const info = await this.props.context.httpClient.get('https://ipinfo.io/json');
    const locinfo = await info.json();
    const [latitude, longitude] = locinfo.loc.split(',').map(Number);

    // Step 2: Call OpenWeather API using coordinates
    const weather = await this.props.context.httpClient.get(
      'https://cors.5apps.com/?uri=http://api.openweathermap.org/data/2.5/weather?lat=' +
      latitude +
      '&lon=' +
      longitude +
      '&units=metric&APPID=c3e00c8860695fd6096fe32896042eda'
    );

    const weatherinfo = await weather.json();

    // Step 3: Process API data
    const windSpeedkmh = Math.round(weatherinfo.wind.speed * 3.6);
    const Celsius = Math.round(weatherinfo.main.temp);
    const iconId = weatherinfo.weather[0].icon;
    const weatherURL = 'http://openweathermap.org/img/w/' + iconId + '.png';

    // Step 4: Update state to display weather
    this.setState({
      skyimage: weatherURL,
      location: locinfo.city + ', ' + locinfo.region + ', ' + locinfo.country,
      weatherid: weatherinfo.weather[0].description,
      temperature: Celsius.toString(),
      windspeed: windSpeedkmh + ' km/hr',
      humidity: weatherinfo.main.humidity
    });
  }
}

💡 Explanation

  • ipinfo.io/json → Detects user’s location via IP address.
  • OpenWeather API → Fetches live weather details using latitude and longitude.
  • Uses CORS proxy (5apps.com) to bypass browser restrictions.
  • The resulting JSON is parsed and stored in React state to display the UI.

🧠 Example Output

Location: London, England, GB
Sky: Overcast clouds
Temperature: 21°C
Wind Speed: 9 km/hr
Humidity: 62%


🚀 Deploy the Solution

Build and package your solution:

gulp build
gulp bundle --ship
gulp package-solution --ship

Then upload the .sppkg file to your App Catalog and deploy it.
You can now add the Local Weather Forecast web part to any SharePoint page.


📂 GitHub Source

View full SPFx project on GitHub:Local Weather Forecast in SPFx

GitHub

✅ Summary

This SPFx web part automatically detects the user’s location and fetches weather details using the OpenWeather API — no manual configuration needed.
It’s lightweight, fully client-side, and works in any SharePoint modern site.

Calendar IconBook a demo