LoginSignup
1
1

More than 5 years have passed since last update.

郵便番号をキーにして、OpenWeatherMapから天気データを読み込んでkintoneに表示させるメモ

Last updated at Posted at 2019-02-09

デベロッパーネットワークの投稿を元に試してみたメモです。
https://developer.cybozu.io/hc/ja/community/posts/360041094612

好きなAPI kintone.proxy が使われていたので、元のソースコードをお借りして修正してみました。

ソースコード

index.js
(function() {
    "use strict";
    // 編集画面と新規作成画面にて
    kintone.events.on(['app.record.edit.show','app.record.create.show'], function(event) {
        // ボタンを作成
        var getWeatherBtn = document.createElement('button');
        getWeatherBtn.id = 'get_weather_btn';
        getWeatherBtn.innerText = '天気を取得する';

        // ボタンクリックイベントで発火
        getWeatherBtn.onclick = function () {
            console.log(event);
            // レコード取得
            var record = kintone.app.record.get();
            console.log(record);
            // 郵便番号フィールドから入力値を取得
            var zipCode = record.record.郵便番号.value;
            console.log(zipCode);
            var apiKey = '1234567890abcdefg'; // OpenWeatherMapのAPIキー
            var owmUrl = 'https://api.openweathermap.org/data/2.5/weather?zip=' + zipCode + ',jp' + '&APPID=' + apiKey ;
            console.log(owmUrl);
            // return new kintone.Promise(function(resolve, reject) {
            // イベントをreturnしない。
            new kintone.Promise(function(resolve, reject) {
                kintone.proxy(owmUrl, 'GET', {}, {}, function(body, status, headers){
                    if (status >= 200 && status < 300) {
                        var json = body.replace(/^\s+|\s+$/g,''); 
                        var result = JSON.parse(json);
                        console.log(result);
                        var todayWeather = result.weather[0].main;
                        console.log(todayWeather);
                        record.record.天気.value = todayWeather;
                        // レコードセット
                        kintone.app.record.set(record);
                        resolve(event);
                    }
                },function(error) {
                    //error
                    console.log(error); 
                    resolve(event);
                });
            });
        };
        // ボタンの描画
kintone.app.record.getSpaceElement('get_weather_btn_field').appendChild(getWeatherBtn);
    });
})();

画面イメージ

スクリーンショット 2019-02-10 7.07.03.png

まとめ

  • イベントをリターンしない事が肝
  • OpenWeatherMapは無料枠がある

リンク

1
1
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
1
1