2
9

More than 3 years have passed since last update.

Node.jsでお天気を取得してみよう

Last updated at Posted at 2020-04-26

はじめに

OpenWeatherMap APIからお天気情報を取得しようという試みです。
色々な方が、さまざまな言語で同様の記事を上げています。
私は、勉強真っ最中のNode.jsでやってみようと思いました。
(Node.jsの導入はこちら)

環境

wslの環境です。

Editor: VSCode
Shell : bash version 4.4.20
Ubuntu: 18.04.4 LTS
node  : v10.14.2

1.APIの取得

OpenWeatherMapの公式サイトで無料アカウントを作成後、
表示されるAPIキーを控えておいてください。
APIキー取得後は少し時間をおいてか試したほうがいいと思います。
公式もそういってますし。

2.プロジェクトを作成

1.任意の位置(緯度経度)のお天気情報を取得

とりあえず福岡市にしてみました。

app.js
'use strict';

const http = require('http');
const MY_WEATHER_APIKEY = {YOUR_API_KEY};
const LAT = 33.60639;  //緯度
const LON = 130.41806;  //経度
const req = 'http://api.openweathermap.org/data/2.5/weather?lat='+LAT+'&lon='+LON+'&appid='+ MY_WEATHER_APIKEY;

http.get(req, res => {
  var body ='';
  res.setEncoding('utf8');
  res.on('data', (chunk) => {
    body += chunk;
  });
  res.on('end', () => {
    res = JSON.parse(body);
    console.log(res);
  });
})
  .on('error', e => {
    console.error(e.message);
});

{YOUR_API_KEY}に控えておいたAPIキーを入れてください。

実行結果

$ node scripts/app.js 
{ coord: { lon: 130.42, lat: 33.61 },
  weather:
   [ { id: 803,
       main: 'Clouds',
       description: 'broken clouds',
       icon: '04n' } ],
  base: 'stations',
  main:
   { temp: 286.85,
     feels_like: 284.37,
     temp_min: 285.93,
     temp_max: 287.15,
     pressure: 1018,
     humidity: 58 },
  visibility: 10000,
  wind: { speed: 2.1, deg: 300 },
  clouds: { all: 75 },
  dt: 1587901760,
  sys:
   { type: 1,
     id: 7998,
     country: 'JP',
     sunrise: 1587846896,
     sunset: 1587895019 },
  timezone: 32400,
  id: 1863967,
  name: 'Fukuoka',
  cod: 200 }

この結果をいろいろ触って特定の情報を抜き出せます。

weather:
[ { id: 803,
main: 'Clouds',
description: 'broken clouds',
icon: '04n' } ]

が欲しければ、console.log(res.weather);

main: 'Clouds'

が欲しければ、console.log(res.weather[0].main);
という風にすればいいですね。
おぉ、いま福岡の方は曇りなんですね。

2.モジュール化

うまくいったので、モジュール化しました。
のちのちモジュール化しておいたほうが使いまわしやすいと思います。

app.js
'use strict';
const weather = require('./weatherFunc');
const MY_WEATHER_APIKEY = {YOUR_API_KEY};
weather.clweather(MY_WEATHER_APIKEY);
weatherFunc.js
'use strict';
const http = require('http');

function clweather(api){
  const LAT = 33.60639;  //緯度
  const LON = 130.41806;  //経度
  const req = 'http://api.openweathermap.org/data/2.5/weather?lat='+LAT+'&lon='+LON+'&appid='+ api;
  http.get(req, res => {
    let body ='';
    res.setEncoding('utf8');
    res.on('data', (chunk) => {
      body = body.concat(chunk);
    });
    res.on('end', () => {
      res = JSON.parse(body);
      console.log(res);
    });
  })
    .on('error', e => {
      console.error(e.message);
  });
}

module.exports = {
  clweather
}

さいごに

今後の展望としては、現在地の自動取得とか取り入れていけば、
経度、緯度指定にしていることが活きてきて、
もう少し実用的になると思います。

拙い文章でしたしょうが、お付き合いありがとうございました。

さよなら:wave:

関連記事

参考

2
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
9