Node.jsからDark Sky APIを用いて天気情報を得る
3連休はあいにくの天気。のんびりとNode.jsを学習中です。
今日はDark Sky APIを用いた簡単なサンプルプログラムを試しました。
この機能を使えば、Fitbit Ionicのオリジナルのクロックフェース(文字盤)に天気予報を出すこともできそうですね。
仕様及び非機能要件
- 引数で指定した天気予報の概要、現在の気温、降水確率の文字列を出力する。「結果」参照。
- 気温は摂氏(℃)。
- 概要情報は日本語とする。
- 数値を指定桁で四捨五入する。
- Dark Sky APIを使用する。
- HTTPリクエストを簡単にするnpmのrequestモジュール使用する。
- インターネット接続が切れた場合、エラーメッセージを表示する。
- APIの呼び出し結果がエラーだった場合、エラーメッセージを表示する。
- エラーメッセージは、赤字の反転とする。
- ES6のDestructuringとProperty shothandを使用する。

結果
PS > node app.js 仙台市 日本, 宮城県仙台市 の天気予報をお伝えします。 一週間中降水なし。水曜日は最高気温34°C。 現在の気温は28.0℃、降水確率は9%です。
コード
- 下記のxxxxと伏せ字にしている部分は、APIのシークレットキー
app.js
const chalk = require('chalk')
const geocode = require('./utils/geocode')
const forecast = require('./utils/forecast')
const address = process.argv[2]
if (!address) {
return console.log(chalk.red.inverse('天気予報を表示するための住所を指定してください。'))
}
geocode(address, (error, { latitude, longtitude, location } = {}) => {
if (error) {
return console.log(chalk.red.inverse(error))
}
forecast(latitude, longtitude, (error, {summary, temperature, probability}) => {
if (error) {
return console.log(chalk.red.inverse(error))
}
console.log(location + ' の天気予報をお伝えします。')
console.log(summary)
console.log('現在の気温は'+temperature+'℃、降水確率は'+probability+'%です。')
})
})
utils/forecast.js
const request = require('request')
const forecast = (latitude, longitude, callback) => {
const url = 'https://api.darksky.net/forecast/xxxxxx/' + latitude + ',' + longitude + '?lang=ja&units=si' // 秘密です
request ( { url, json: true }, (error, { body }) => {
if (error) {
callback ('天気サービスに接続できません'.undefined)
} else if (body.error) {
callback('その地域の天気情報を得ることができません', undefined)
} else {
callback(undefined, {
summary: body.daily.summary,
temperature: body.currently.temperature.toFixed(1),
probability: (body.currently.precipProbability * 100).toFixed(0)
})
}
})
}
module.exports = forecast
utils/geocode.js
const request = require('request')
const geocode = (address, callback) => {
const mapBoxAccessToken = 'pk***' // 秘密です
const url = 'https://api.mapbox.com/geocoding/v5/mapbox.places/' + encodeURIComponent(address) + '.json?access_token=' + mapBoxAccessToken + '&limit=1&language=ja'
request ( {url: url, json: true}, (error, { body }) => {
if (error) {
callback('ロケーションサービスに接続できません', undefined)
} else if (body.features.length === 0) {
callback('指定した地域の緯度・経度を得ることができません', undefined)
} else {
callback(undefined, {
latitude: body.features[0].center[1],
longtitude: body.features[0].center[0],
location: body.features[0].place_name
})
}
})
}
module.exports = geocode
プロジェクト設定
ソースコードのフォルダにて以下を実行する。
npm init -y // -yにより対話なしでデフォルトを受け入れてpackage.jsonを生成する npm i request@2.88.0 // バージョン2.88.0のrequestモジュールを本プロジェクトにインストールする
Dark Sky APIのアカウント設定
- https://darksky.net/dev にアクセスする。
- [TRY FOR FREE]ボタンをクリックする。
- Registerページで電子メールアドレス、パスワードを設定し、[REGISTER]ボタンをクリックする。
- 送られてきたメールのリンクをクリックする。







ディスカッション
コメント一覧
まだ、コメントがありません