顧客訪問リストを地図にピン表示する

目次

warning
注意

2020 年 8 月改訂のセキュアコーディング ガイドライン に抵触する内容が含まれています。
認証情報が漏洩した場合の影響を考慮して慎重に検討してください。
該当箇所:JavaScript プログラムの 13 行目

概要

アプリのレコード一覧表示時、顧客の住所をもとに地図上でピンを表示します。
詳細画面での地図表示も行います。

information

サンプルでは、Google Maps Platform の Maps JavaScript API を使用しています。
ご利用方法によっては有償ライセンスの購入が必要になります。
Google のライセンスを確認してください。

完成形

下準備

サンプルプログラム

プログラム

13 行目の Your Google API key の部分を取得した Maps JavaScript API キーに書き換えてください。

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
/*
 * 一覧画面に地図を表示するサンプルプログラム
 * Copyright (c) 2016 Cybozu
 *
 * Licensed under the MIT License
 * https://opensource.org/license/mit/
 */

(function() {

  'use strict';
  // API キー
  const api_key = 'Your Google API key';

  // ヘッダに要素を追加します
  function load(src) {
    const head = document.getElementsByTagName('head')[0];
    const script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = src;
    head.appendChild(script);
  }

  // 緯度、経度を空にします
  function emptyLatLng(event) {

    // event よりレコード情報を取得します
    const rec = event.record;

    // 保存の際に緯度、経度を空にします
    rec.lat.value = '';
    rec.lng.value = '';
    return event;

  }

  // Google Map を Load します
  function loadGMap() {

    // document.write を定義します
    const nativeWrite = document.write;
    document.write = function(html) {
      const m = html.match(/script.+src="([^"]+)"/);
      if (m) {
        load(m[1]);
      } else {
        nativeWrite(html);
      }
    };

    // Google Map の API ライブラリをロードします
    load('https://maps.googleapis.com/maps/api/js?v=3&key=' + api_key);

  }

  // 地図を「住所」フィールドの下に表示します
  // 緯度・経度がない場合は、住所をもとに緯度・経度を算出し、
  // フィールドに値を入れた後、レコードを更新します
  function setLocationDetail(event) {

    // レコード情報を取得します
    const rec = event.record;

    // Google Geocoder を定義します
    const gc = new google.maps.Geocoder();

    // 住所が入力されていなければ、ここで処理を終了します
    if (rec['住所'].value === undefined) {
      return;
    }
    if (rec['住所'].value.length === 0) {
      return;
    }

    // 緯度・経度が入力されていなければ、住所から緯度・経度を算出します
    if (rec.lat.value === undefined ||
            rec.lng.value === undefined ||
            rec.lat.value.length === 0 ||
            rec.lng.value.length === 0) {

      // Geocoding API を実行します
      gc.geocode({
        address: rec['住所'].value,
        language: 'ja',
        country: 'JP'
      }, (results, status) => {

        // 住所が検索できた場合、開いているレコードに対して
        // 緯度・経度を埋め込んで更新します
        if (status === google.maps.GeocoderStatus.OK) {

          // 更新するデータの Object を作成します
          const objParam = {};
          objParam.app = kintone.app.getId();// アプリ番号
          objParam.id = kintone.app.record.getId(); // レコードID
          objParam.record = {};
          objParam.record.lat = {}; // 緯度
          objParam.record.lat.value = results[0].geometry.location.lat();
          objParam.record.lng = {}; // 経度
          objParam.record.lng.value = results[0].geometry.location.lng();

          // レコードを更新します
          kintone.api(kintone.api.url('/k/v1/record', true), 'PUT', objParam, (resp) => {
            // 成功時は画面をリロードします
            location.reload(true);
          }, (resp) => {
            // エラー時はメッセージを表示して、処理を中断します
            alert('error->' + resp);

          });
        }
      });
    }

    // 地図を表示する div 要素を作成します
    const mapEl_address = document.createElement('div');
    mapEl_address.setAttribute('id', 'map_address');
    mapEl_address.setAttribute('name', 'map_address');
    mapEl_address.setAttribute('style', 'width: 300px; height: 250px');

    // 「Map」スペース内に mapEl_address で設定した要素を追加します
    const elMap = kintone.app.record.getSpaceElement('Map');
    elMap.appendChild(mapEl_address);

    // 「Map」スペースの親要素のサイズを変更します
    const elMapParent = elMap.parentNode;
    elMapParent.setAttribute('style', 'width: 300px; height: 250px');

    // ポイントする座標を指定します
    const point = new google.maps.LatLng(rec.lat.value, rec.lng.value);

    // 地図の表示の設定(中心の位置、ズームサイズ等)を設定します
    const opts = {
      zoom: 15,
      center: point,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      scaleControl: true
    };

    // 地図を表示する要素を呼び出します
    const map_address = new google.maps.Map(document.getElementById('map_address'), opts);

    // マーカーを設定します
    const marker = new google.maps.Marker({
      position: point,
      map: map_address,
      title: rec['住所'].value
    });

  }

  // 地図を一覧画面のメニュー下のスペースに表示します
  function setLocationIndex(event) {

    const lat = [];
    const lng = [];
    const recno = [];
    let i;

    // レコード情報を取得します
    const rec = event.records;

    // 一覧に表示されているすべてのレコードの緯度・経度とレコードIDを配列に格納します
    for (i = 0; i < rec.length; i += 1) {
      if (rec[i].lat.value !== undefined && rec[i].lng.value !== undefined) {
        if (rec[i].lat.value.length > 0 && rec[i].lng.value.length > 0) {
          lat.push(parseFloat(rec[i].lat.value)); // 緯度
          lng.push(parseFloat(rec[i].lng.value)); // 経度
          recno.push(parseFloat(rec[i].$id.value)); // レコードID
        }
      }
    }

    // 一覧の上部部分にあるスペース部分を定義します
    const elAction = kintone.app.getHeaderSpaceElement();

    // すでに地図要素が存在する場合は、削除します
    // ※ ページ切り替えや一覧のソート順を変更した時などが該当します
    const check = document.getElementsByName('map');
    if (check.length !== 0) {
      elAction.removeChild(check[0]);
    }

    // 地図を表示する要素を定義し、スペース部分の要素に追加します
    const mapEl = document.createElement('div');
    mapEl.setAttribute('id', 'map');
    mapEl.setAttribute('name', 'map');
    mapEl.setAttribute('style', 'width: auto; height: 250px; margin-right: 30px; border: solid 2px #c4b097');
    elAction.appendChild(mapEl);

    // 一覧に表示されているレコードで、緯度・経度の値が入っている
    // 一番上のレコードの緯度・経度を取得します(地図の中心になります)
    let latlng = 0;
    for (i = 0; i < lat.length; i += 1) {
      if (isNaN(lat[i]) === false && isNaN(lng[i]) === false) {
        latlng = new google.maps.LatLng(lat[i], lng[i]);
        break;
      }
    }

    // もし、緯度・経度に値が入っているレコードがなければ、ここで処理を終了します
    if (latlng === 0) {
      return;
    }

    // 表示する地図の設定を行います
    const opts = {
      zoom: 12,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      scaleControl: true,
      title: 'target'
    };

    // 地図の要素を定義します
    const map = new google.maps.Map(document.getElementById('map'), opts);
    const marker = [];
    const m_latlng = [];

    // 緯度・経度をもとに、地図にポインタを打ち込みます
    for (i = 0; i < lat.length; i += 1) {
      if (isNaN(lat[i]) === false && isNaN(lng[i]) === false) {
        m_latlng[i] = new google.maps.LatLng(lat[i], lng[i]);
        marker[i] = new google.maps.Marker({
          position: m_latlng[i],
          map: map,
          // ポインタのアイコンは Google Charts を使用します
          icon: 'https://chart.googleapis.com/chart?chst=d_bubble_text_small&chld=edge_bc|'
                    + recno[i] + '|FF8060|000000'
        });
      }
    }
  }

  // Google Map がロードされるまで待機します
  function waitLoaded(event, mode, timeout, interval) {
    setTimeout(() => {
      const setTimeout = timeout - interval;
      if ((typeof google !== 'undefined')
                && (typeof google.maps !== 'undefined')
                && (typeof google.maps.version !== 'undefined')) {

        if (mode === 'detail') { // 詳細画面の場合
          setLocationDetail(event);
        } else if (mode === 'index') { // 一覧画面の場合
          setLocationIndex(event);
        }
      } else if (setTimeout > 0) { // ロードされるまで繰り返します
        waitLoaded(event, mode, setTimeout, interval);
      }
    }, interval);
  }

  // 詳細画面を開いた時に実行します
  function detailShow(event) {
    loadGMap();
    waitLoaded(event, 'detail', 10000, 100);
  }

  // 一覧画面を開いた時に実行します
  function indexShow(event) {
    loadGMap();
    waitLoaded(event, 'index', 10000, 100);
  }

  // 一覧画面で編集モードになった時に実行されます
  function indexEditShow(event) {
    const record = event.record;
    // 住所フィールドを使用不可にします
    record['住所'].disabled = true;
    return event;
  }

  // 登録・更新イベント(新規レコード、編集レコード、一覧上の編集レコード)
  kintone.events.on(['app.record.create.submit',
    'app.record.edit.submit',
    'app.record.index.edit.submit'], emptyLatLng);

  // 詳細画面が開いた時のイベント
  kintone.events.on('app.record.detail.show', detailShow);

  // 一覧画面が開いた時のイベント
  kintone.events.on('app.record.index.show', indexShow);

  // 一覧画面で編集モードにした時のイベント
  kintone.events.on('app.record.index.edit.show', indexEditShow);

})();
  1. エディターにサンプルプログラムをコピーし、ファイル名を sample.js 、文字コードを UTF-8 にして保存します。
    ファイル名は任意です。
  2. 準備したアプリの設定画面で、保存したファイルを読み込みます。
  3. アプリの設定を完了します。

使用した API

変更履歴

  • 2018/07/18
    • Maps JavaScript API キーを使用したコードに修正