天気予報API
天気予報を取得するにあたってLivedoor Weather Web ServiceというAPIを用いていきたいと思います。
リクエストを送るURLはこちら。
http://weather.livedoor.com/forecast/webservice/json/v1?city=【調べたい地域のID番号】
例) http://weather.livedoor.com/forecast/webservice/json/v1?city=130010
このID番号はこちらから確認することができます。
1次細分区定義表 - livedoor 天気情報
実際にリクエストを送るとこのようなJSONが返ってきました。
{ "pinpointLocations": [ { "link": "http://weather.livedoor.com/area/forecast/1310100", "name": "千代田区" }, (以下省略) ], "link": "http://weather.livedoor.com/area/forecast/130010", "forecasts": [ { "dateLabel": "今日", "telop": "曇り", "date": "2019-11-03", "temperature": { "min": null, "max": null }, "image": { "width": 50, "url": "http://weather.livedoor.com/img/icon/8.gif", "title": "曇り", "height": 31 } }, { "dateLabel": "明日", "telop": "晴時々曇", "date": "2019-11-04", "temperature": { "min": { "celsius": "12", "fahrenheit": "53.6" }, "max": { "celsius": "20", "fahrenheit": "68.0" } }, "image": { "width": 50, "url": "http://weather.livedoor.com/img/icon/2.gif", "title": "晴時々曇", "height": 31 } }, { "dateLabel": "明後日", "telop": "晴時々曇", "date": "2019-11-05", "temperature": { "min": null, "max": null }, "image": { "width": 50, "url": "http://weather.livedoor.com/img/icon/2.gif", "title": "晴時々曇", "height": 31 } } ], "location": { "city": "東京", "area": "関東", "prefecture": "東京都" }, "publicTime": "2019-11-03T21:00:00+0900", "copyright": { "provider": [ { "link": "http://tenki.jp/", "name": "日本気象協会" } ], "link": "http://weather.livedoor.com/", "title": "(C) LINE Corporation", "image": { "width": 118, "link": "http://weather.livedoor.com/", "url": "http://weather.livedoor.com/img/cmn/livedoor.gif", "title": "livedoor 天気情報", "height": 26 } }, "title": "東京都 東京 の天気", "description": { "text": " 低気圧が伊豆諸島付近にあって、東北東へ進んでいます。\n\n 東京地方は、曇りで雨や雷雨となっている所があります。\n\n 3日は、低気圧の影響により、曇りで雨や雷雨となる所があるでしょう。伊豆諸島では雷を伴って激しく降る所がある見込みです。\n\n 4日は、大陸の高気圧が本州付近に張り出すため晴れますが、気圧の谷や寒気の影響により、時々曇りで、明け方まで雨や雷雨となる所があるでしょう。伊豆諸島では雨や雷雨となる所がある見込みです。\n\n【関東甲信地方】\n 関東甲信地方は曇りで、伊豆諸島や関東地方南部では雨や雷雨となっている所があります。\n\n 3日は、低気圧の影響により、曇りで雨や雷雨となる所があるでしょう。伊豆諸島では激しく降る所がある見込みです。\n\n 4日は、大陸の高気圧が本州付近に張り出すため晴れますが、気圧の谷や寒気の影響により、朝晩を中心に曇りで雨の降る所があるでしょう。伊豆諸島では雷を伴う所がある見込みです。\n\n 関東地方と伊豆諸島の海上では、4日にかけて波がやや高いでしょう。", "publicTime": "2019-11-03T21:16:00+0900" } }
結構色々な情報が含まれているようですね。これを使ってスクリプトを書いてみましょう。
コード
function getWeater() { // 「Livedoor Weather Web Service」というAPIを用いて天気を取得 (city=130010は東京) var response = UrlFetchApp.fetch('http://weather.livedoor.com/forecast/webservice/json/v1?city=130010'); // getContentTextメソッドにて純粋なテキストデータを取り出し、parseメソッドで解析して格納 var json = JSON.parse(response.getContentText()); Logger.log("地域: " + json["location"]["city"]); Logger.log("天候: " + json["forecasts"][0]["telop"]); }
最高気温・最低気温なんかも取得できますが、どうやらnull
になっている場合があるらしく注意が必要です。
Logger.log("最高気温: " + json["forecasts"][0]["temperature"]["max"]["celsius"]); Logger.log("最低気温: " + json["forecasts"][0]["temperature"]["min"]["celsius"]);
さいごに
これをLINEやSlackなどに送信してみたりすると面白いかもしれませんね。
是非上手く活用してみてください!