Labo288

プログラミングのこと、GISのこと、パソコンのこと、趣味のこと

静的なGeoJSONファイルを読み込んでLeafletにレイヤーを追加する

概要

GeoJSONファイルとは、以下のとおり、ある程度データの構造が予め規定されたJSON形式のファイルです。

{ "type": "FeatureCollection",
  "features": [
    { "type": "Feature",
      "geometry": {"type": "Point", "coordinates": [102.0, 0.5]},
      "properties": {"prop0": "value0"}
      },
    { "type": "Feature",
      "geometry": {
        "type": "LineString",
        "coordinates": [
          [102.0, 0.0], [103.0, 1.0], [104.0, 0.0], [105.0, 1.0]
          ]
        },
      "properties": {
        "prop0": "value0",
        "prop1": 0.0
        }
      },
    { "type": "Feature",
       "geometry": {
         "type": "Polygon",
         "coordinates": [
           [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0],
             [100.0, 1.0], [100.0, 0.0] ]
           ]
       },
       "properties": {
         "prop0": "value0",
         "prop1": {"this": "that"}
         }
       }
     ]
   }

引用元:https://s.kitazaki.name/docs/geojson-spec-ja.html

ご覧のとおりJSON形式である事には変わりないので、JavaScriptのオブジェクトとして読み込めます。 また、GeoJSON形式のオブジェクトであれば、Leaflet.jsはデフォルトで読み込みに対応しています。 静的ファイルをサーバーに置いてLeafletで表示したい、という事があると思いますので、以下にコード例を示します。

function addGeoJSONLayer(geojson){
    var geojsonLayer = L.geoJSON(geojson,{
        onEachFeature: function (feature, layer) {
            //簡素化
            layer.options.smoothFactor = 1.5;

        }
    });
    //GEOJSONレイヤーをオーバーレイレイヤーに追加
    map.addLayer(geojsonLayer);
};

これはGeoJSON形式のオブジェクトを引数として、Leafletマップにレイヤーを追加する関数です。 以下に示す、静的ファイルの内容をFetchによる非同期通信で取得する関数と組み合わせます。

function getJSON(jsonUrl) {
    fetch(jsonUrl, {
        method:"GET"
    })
    .then(function(response) {
        console.log("status=" + response.status); 
        return response.json();
    })
    .then(function(data) {
        addGeoJSONLayer(data);
    })
    .catch(function(err1) {
        console.log("err=" + err1);
    });
};

ここで、jsonUrlはGeoJSON形式のファイルへのURLです。 GETでリクエストし、取得したJSON形式の文字列をJavaScriptオブジェクトへ変換、前述の関数へ渡しています。