変換表を別ファイルで管理したい

国土地理院のAPIを使用して逆ジオコーディングで現在地から取得した緯度・経度情報を基に住所を自動入力する機能を作成しているのですが、県と市区町村がコードで管理されているため変換表を作成して変換をしています。

しかし、この変換表はコード内にべた書きしており、非常にコードが見にくくなっています。

ですので変換表のみを別ファイルで管理し、そのファイルを読み込み変換する方法について教えていただきたいです。

まだjavascriptに触れて1年もたっていないため煩雑なコードになっているとは思いますがよろしくお願いします。

====以下現状のコード====

(function() {

  ‘use strict’;

  let map;

  let marker;

   /** 変換表を入れる場所 */

   GSI.MUNI_ARRAY = {};

GSI.MUNI_ARRAY[“1100”] = ‘1,北海道,1100,札幌市’;

GSI.MUNI_ARRAY[“1101”] = ‘1,北海道,1101,札幌市 中央区’;

GSI.MUNI_ARRAY[“1102”] = ‘1,北海道,1102,札幌市 北区’;

GSI.MUNI_ARRAY[“1103”] = ‘1,北海道,1103,札幌市 東区’;

//省略

GSI.MUNI_ARRAY[“47375”] = ‘47,沖縄県,47375,多良間村’;

GSI.MUNI_ARRAY[“47381”] = ‘47,沖縄県,47381,竹富町’;

GSI.MUNI_ARRAY[“47382”] = ‘47,沖縄県,47382,与那国町’;

 

  kintone.events.on([‘app.record.detail.show’,‘mobile.app.record.detail.show’,‘app.record.print.show’], function(event) {  

    createMap();

    map.panTo([event.record.緯度.value,event.record.経度.value]);

    marker.setLatLng([event.record.緯度.value,event.record.経度.value]);

  });

 

  kintone.events.on([‘app.record.create.show’,‘app.record.edit.show’,‘mobile.app.record.create.show’,‘mobile.app.record.edit.show’], function(event) {

    createMap();

    marker.dragging.enable();

    marker.on(‘dragend’, function(event) {

      let position = marker.getLatLng();

      let record = kintone.app.record.get().record;

      record.緯度.value = position.lat;

      record.経度.value = position.lng;

      kintone.app.record.set({record});

    });

   

    //緯度経度未設定ならGPS取得

    if(!event.record.緯度.value || !event.record.経度.value){

      let success = function(position){

        let record = kintone.app.record.get().record;

        record.緯度.value = position.coords.latitude;

        record.経度.value = position.coords.longitude;

        kintone.app.record.set({record});

        console.log(“緯度:”+position.coords.latitude);

        console.log(“経度:”+position.coords.longitude);

      };

   

      let error = function(){

          alert(“現在位置取得失敗”);

      };

     

      let options = {“enableHighAccuracy”:true};

     

      if(navigator.geolocation){

        navigator.geolocation.getCurrentPosition(success,error,options);

      }

    }else{

      map.panTo([event.record.緯度.value,event.record.経度.value]);

      marker.setLatLng([event.record.緯度.value,event.record.経度.value]);

     

    }

  });

 

  kintone.events.on([“app.record.create.change.経度”,“app.record.edit.change.経度”,“mobile.app.record.create.change.経度”,“mobile.app.record.edit.change.経度”], function(event) {

      map.panTo([event.record.緯度.value,event.record.経度.value]);

      marker.setLatLng([event.record.緯度.value,event.record.経度.value]);

   

      //町域取得

      const url =  “https://mreversegeocoder.gsi.go.jp/reverse-geocoder/LonLatToAddress?lat=” + event.record.緯度.value + “&lon=” + event.record.経度.value;

      kintone.proxy(url, ‘GET’, {}, {}, (body, status, headers) => {

        let result = JSON.parse(body);

        let record = kintone.app.record.get().record;

        if(result.results.muniCd !== “”){

        // 変換表から都道府県などを取得

        const muniData = GSI.MUNI_ARRAY[result.results.muniCd];

        if(result.results.muniCd in GSI.MUNI_ARRAY){

            // 都道府県コード,都道府県名,市区町村コード,市区町村名 に分割

        const [prefCode, pref, muniCode, city] = muniData.split(‘,’);

        record.県.value = ${pref};

        record.市区町村.value = ${city};

        record.町域.value = result.results.lv01Nm;

        kintone.app.record.set({record});

        }else{

          record.市区町村.value = “”;

          record.町域.value = result.results.lv01Nm;

          kintone.app.record.set({record});

        }}else{

          record.市区町村.value = “”;

          record.町域.value = “”;

          alert(“市区町村”);

        }

       

      }, (error) => {

        // error

        //console.log(error); // proxy APIのレスポンスボディ(文字列)を表示

      });

  });

 

  function createMap(){

    let se = kintone.app.record.getSpaceElement(“map”);

   

    let div = document.createElement(“div”);

    div.id = “map”;

    div.style.width = “500px”;

    div.style.height = “500px”;

    se.append(div);

   

    map = L.map(‘map’);

   

    // OpenStreetMap から地図画像を読み込む

     L.tileLayer(‘https://{s}.tile.osm.org/{z}/{x}/{y}.png’, {

         maxZoom: 18,

         attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, ’

     }).addTo(map);

   

    map.setView([33.8419414,132.7656902], 18);

   

    marker = new L.marker([33.8419414,132.7656902]);

    map.addLayer(marker);    

  }

})();

https://ribbit.konomi.app/blog/kintone-global-variable

すぐできるのは上記ページにある「グローバル変数・定数をアプリ内で定義する」か「グローバル定数をkintone全体に定義する」をやることですね。

 

もう一つの方法として、少し学習コストがかかりますが、下記のようにbundle(書くときは複数ファイルだが、最終的には自動で一つのファイルに纏める)するようにするとやりたいことは実現できます。一度下記をよんでみてください。

https://cybozudev.zendesk.com/hc/ja/articles/360040220451-%E7%9B%AE%E6%8C%87%E3%81%9B-JavaScript%E3%82%AB%E3%82%B9%E3%82%BF%E3%83%9E%E3%82%A4%E3%82%BA%E4%B8%AD%E7%B4%9A%E8%80%85-%EF%BC%91-webpack%E7%B7%A8-

返信が遅れて申し訳ありません。

1つ目の方法を試してみようと思います。

追加で質問なのですが以下のような認識で合っていますでしょうか?

(() => {
 window.RIBBIT = window.RIBBIT || {};
 RIBBIT.GSI = {
   let GSI = RIBBIT.GSI;
GSI.MUNI_ARRAY = {};
GSI.MUNI_ARRAY["1100"] = '1,北海道,1100,札幌市';
GSI.MUNI_ARRAY["1101"] = '1,北海道,1101,札幌市 中央区';
GSI.MUNI_ARRAY["1102"] = '1,北海道,1102,札幌市 北区';
GSI.MUNI_ARRAY["1103"] = '1,北海道,1103,札幌市 東区';

/*省略*/

GSI.MUNI_ARRAY["47362"] = '47,沖縄県,47362,八重瀬町';
GSI.MUNI_ARRAY["47375"] = '47,沖縄県,47375,多良間村';
GSI.MUNI_ARRAY["47381"] = '47,沖縄県,47381,竹富町';
GSI.MUNI_ARRAY["47382"] = '47,沖縄県,47382,与那国町';
  },
 };
})();

このトピックはベストアンサーに選ばれた返信から 3 日が経過したので自動的にクローズされました。新たに返信することはできません。