住所から地図を表示する

目次

caution
警告

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

概要

レコード詳細画面の表示時、「住所」に入力されている地点を地図上で表示します。

サンプルでは、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
/*
 * 地図表示のサンプルプログラム
 * Copyright (c) 2013 Cybozu
 *
 * Licensed under the MIT License
 * https://opensource.org/license/mit/
 */

(() => {

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

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

  // Google Maps APIをロード
  const loadGMap = () => {
    // document.write を定義
    const nativeWrite = document.write;
    document.write = (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);
  };

  // レコード表示時イベントで住所フィールドの値を利用して地図を表示する
  kintone.events.on('app.record.detail.show', (event) => {

    // 住所情報を元に、地図を「住所」フィールドの下に表示します
    const drawMap = () => {
      if (kintone.app.record.getFieldElement('住所').length === 0) {
        return;
      }
      // 「map_address」という要素が存在しないことを確認
      if (document.getElementsByName('map_address').length !== 0) {
        return;
      }

      // 地図を表示する div 要素を作成します
      const mapAddressEl = document.createElement('div');
      mapAddressEl.setAttribute('id', 'map_address');
      mapAddressEl.setAttribute('name', 'map_address');

      // 「住所」フィールドに設置したスペースフィールドに mapAddressEl で設定した要素を追加します
      const space = kintone.app.record.getSpaceElement('Map');
      space.appendChild(mapAddressEl);

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

      // 「住所」フィールドから値を取得します
      const rec = kintone.app.record.get();
      const addressValue = rec.record.住所.value;

      // Geocoding API を実行します
      gc.geocode({
        address: addressValue,
        language: 'ja',
        country: 'JP'
      }, (results, status) => {
        if (status === google.maps.GeocoderStatus.OK) {

          // 地図要素のサイズを指定します
          mapAddressEl.setAttribute('style', 'width: 300px; height: 250px');

          const point = results[0].geometry.location;
          const address = results[0].formatted_address;

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

          // マーカーを設定します
          new google.maps.Marker({
            position: point,
            map: map,
            title: address
          });
        }
      });
    };

    // Google Map がロードされるまで待ちます
    const waitLoaded = (_timeout, interval) => {
      setTimeout(() => {
        const timeout = _timeout - interval;
        if ((typeof google !== 'undefined')
              && (typeof google.maps !== 'undefined')
              && (typeof google.maps.version !== 'undefined')) {
          drawMap(); // 住所をもとに地図を表示
        } else if (_timeout > 0) {
          waitLoaded(timeout, interval);
        }
      }, interval);
    };

    if (document.getElementsByName('map_latlng').length === 0) {
      loadGMap();
      waitLoaded(10 * 1000, 100);
    }
  });

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

使用した kintone JavaScript API

information

この Tips は、2022 年 10 月版 kintone で動作を確認しています。