Open In App

Node.js Open Weather Map API for Weather Forecasts

Last Updated : 08 Oct, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

The Open Weather Map API is very popular as it allows you to request weather forecasts and historical weather data programmatically.
Feature of Open Weather Map API: 
 

  1. It is easy to get started and easy to use.
  2. It is widely used and popular API for Weather Forecasts.

Installation of request module: 
 

  1. You can visit the link to Install Request module. You can install this package by using this command. 
     
  2. npm install request
  3. After installing request module you can check your request version in command prompt using the command. 
     
  4. npm version request
  5. Now go to Open Weather Map website and create an account and get your API KEY.
  6. After that, you can create a folder and add a file, for example index.js. To run this file you need to run the following command. 
     
node index.js

Filename: index.js 
 

index.js




const request = require('request'); 
var API_KEY = 'your_api_key'
  
const forecast = function (latitude, longitude) { 
  
var url = `http://api.openweathermap.org/data/2.5/weather?`
            +`lat=${latitude}&lon=${longitude}&appid=${API_KEY}`
  
    request({ url: url, json: true }, function (error, response) { 
        if (error) { 
            console.log('Unable to connect to Forecast API'); 
        
          else
  
            console.log('It is currently '
                + response.body.main.temp
                + ' degrees out.'
            ); 
  
            console.log('The high today is '
                + response.body.main.temp_max 
                + ' with a low of '
                + response.body.main.temp_min
            ); 
  
            console.log('Humidity today is '
                + response.body.main.humidity
            ); 
        
    }) 
  
var latitude = 22.7196; // Indore latitude 
var longitude = 75.8577; // Indore longitude 
  
// Function call 
forecast(latitude, longitude); 


Steps to run the program: 
 

  1. The project structure will look like this: 
     
  2. project structure

  3. Make sure you have installed request module using following command: 
     
  4. npm install request
  5. Run index.js file using below command: 
     
  6. node index.js

So this is how you can use the Open Weather Map API which allows you to request weather forecasts and historical weather data programmatically.
 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads