Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8902

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

$
0
0

はじめに

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';consthttp=require('http');constMY_WEATHER_APIKEY={YOUR_API_KEY};constLAT=33.60639;//緯度constLON=130.41806;//経度constreq='http://api.openweathermap.org/data/2.5/weather?lat='+LAT+'&lon='+LON+'&appid='+MY_WEATHER_APIKEY;http.get(req,res=>{varbody='';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';constweather=require('./weatherFunc');constMY_WEATHER_APIKEY={YOUR_API_KEY};weather.clweather(MY_WEATHER_APIKEY);
weatherFunc.js
'use strict';consthttp=require('http');functionclweather(api){constLAT=33.60639;//緯度constLON=130.41806;//経度constreq='http://api.openweathermap.org/data/2.5/weather?lat='+LAT+'&lon='+LON+'&appid='+api;http.get(req,res=>{letbody='';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:

関連記事

参考


Viewing all articles
Browse latest Browse all 8902

Trending Articles