Local Weather Forecast in SPFx

This article provides steps to implement the Local Weather Forecast in the SharePoint Framework (SPFx), we use some third party REST API to get the current location based on IP address and we getting local weather forecast using the latitude and latitude, so this web part not required any property configuration, it just automatically picking up the local weather forecast 

Create a new web part project

Open power shell and run following comment to create a new web part by running the Yeoman SharePoint Generator

yo @microsoft/sharepoint

When prompted:

Enter the webpart name as your solution name, and then select Enter.
Select Create a subfolder with solution name for where to place the files.
Select Y to allow the solution to be deployed to all sites immediately.
Select N on the question if solution contains unique permissions.
Select WebPart as the client-side component type to be created.

The next set of prompts ask for specific information about your web part:

Enter your web part name, and then select Enter.
Enter your web part description, and then select Enter.
Select React framework as the framework you would like to use, and then select Enter.

Start Visual Studio Code (or your favorite code editor) within the context of the newly created project folder.

cd .\web part name\
code .

Install the library and required dependencies

npm install @pnp/sp --save

Configure the custom properties

Create a new source code file under the src\webparts\<web part name>\components\ folder of the solution. Call the new file I<web part name>State.ts and use it to create a TypeScript Interface

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

Update the <web part name>.tsx file. First, add some import statements to import the types you defined earlier. Notice the import for I<web part name>Props and I<web part name>State. There are also some imports for the PnP components used to render the UI of the PnP React component and pnp sp imports.

import * as React from 'react';
import styles from './SpfxWeather.module.scss';
import { ISpfxWeatherProps } from './ISpfxWeatherProps';
import { ISpfxWeatherState } from './ISpfxWeatherState';
import { HttpClient, HttpClientResponse } from '@microsoft/sp-http';
import { autobind } from 'office-ui-fabric-react/lib/Utilities';

Replace this render function with the following code.

  public render(): React.ReactElement<ISpfxWeatherProps> {
    return (
      <div className={styles.spfxWeather}>
        <img src={this.state.skyimage}></img><br />
        Location: {this.state.location}<br />
        Skies: {this.state.weatherid}<br />
        Temperature: {this.state.temperature}&deg;C<br />
        Wind speed: {this.state.windspeed}<br />
        Humidity: {this.state.humidity}<br />

Update the React component type declaration and add a constructor, as shown in the following example.

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

Add below event functions and function to get local weather forecast

  private async getWeather() {
    const info = await this.props.context.httpClient.get('https://ipinfo.io/json')
    const locinfo = await info.json();
    var locString = locinfo.loc.split(',');
    var latitude = parseFloat(locString[0]);
    var longitude = parseFloat(locString[1]);
    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();
    var windSpeedkmh = Math.round(weatherinfo.wind.speed * 3.6);
    var Celsius = Math.round(weatherinfo.main.temp)
    var iconId = weatherinfo.weather[0].icon;
    var weatherURL = "http://openweathermap.org/img/w/" + iconId + ".png";
      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

Deploy the solution

You’re now ready to build, bundle, package, and deploy the solution.

Run the gulp commands to verify that the solution builds correctly.

gulp build

Use the following command to bundle and package the solution.

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

Browse to the app catalog of your target tenant and upload the solution package. You can find the solution package under the sharepoint/solution folder of your solution. It is the .sppkg file. After you upload the solution package in the app catalog. you can find and the web part anywhere across the tenant.

Sharing is caring!

If you have any questions, feel free to let me know in the comments section.
Happy coding!!!

6 thoughts on “Local Weather Forecast in SPFx

  1. Anand June 22, 2020 / 12:02 pm


    I am new to sharepoint framework and came across your blog while exploring about the SPFx.

    So this webpart seems to be very interesting and i tried to set up it in my local dev.

    Here i have tried couple of changes while playing around with this webpart.

    I tried to call https://ipgeolocationapi.com/ (https://api.ipgeolocationapi.com/geolocate) which is another API to identify the IP address which seems to be free.

    But I am getting below error:

    Access to fetch at ‘https://api.ipgeolocationapi.com/geolocate’ from origin ‘https://tryfinally-app8df77666989e48db880a9bb85d690abe.sharepoint.com’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled

    So to encounter this issue I wrapped this with https://cors-anywhere.herokuapp.com/

    This seems to be working fine but as it hits the above URL so it is picking the address of machine which is hosted this end point which is not correct.

    So I am not sure how we encounter this, any guidance will be really helpful.



    • Ravichandran Krishnasamy June 25, 2020 / 10:29 am

      Hi Anand,

      Issue not reproduced for me, I was tested this in SharePoint Online with chrome browser, please let me know the if you can explain the issue reproduce scenario.


  2. kavitha January 22, 2021 / 12:02 pm

    Hi i have tried the same weather spfx but its showing different location weather forecast ..pls help me on this


      • kavitha January 22, 2021 / 12:13 pm

        thank u so much …working fine


  3. kavitha January 22, 2021 / 12:14 pm

    i need to develop custom page layouts in my SharePoint online (modern) page. Please help me



Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s