LoginSignup
12
11

More than 5 years have passed since last update.

Shapefile を javascript だけで GeoJSON にしてみる

Posted at

はじめに

以前 Shapefile を node.js だけで GeoJSON にして GitHub で確認するまで という記事で shapefile という NPM モジュールを紹介したのですが、バージョンアップに伴っていろいろと変化があったのでポイントを解説します。

この記事では 2016/09 にリリースされた version 0.5.7 を対象としています。

1. インストール

npm で直接インストールできます。

$ npm install shapefile
shapefile@0.5.7 ..\node_modules\shapefile
├── array-source@0.0.3
├── stream-source@0.3.4
├── slice-source@0.4.1
├── text-encoding@0.6.1
├── commander@2.9.0 (graceful-readlink@1.0.1)
└── path-source@0.1.2 (file-source@0.6.1)

以前のバージョンでは古い iconv に依存していた関係で Shift_JIS を扱えず、独自に iconv のバージョンをアップした fork 版など紹介していたのですが、現バージョンでは text-encoding を使うようになり、この問題が解消されました。

2. Node.js での使用

コマンドライン引数で指定した shp ファイルを GeoJSON に変換して加工・出力する例がこちら。

main.js
"use strict";
var shapefile = require("shapefile");

var shp = process.argv[2];

shapefile.read(shp, undefined, {
    encoding: "shift_jis"
  }).then(function(geojson) {
    geojson.features.forEach(function(feature) {
      feature.properties["stroke"] = "#000";
      feature.properties["stroke-opacity"] = 0.8;
      feature.properties["stroke-width"] = 2;
      feature.properties["fill"] = "#ff0";
      feature.properties["fill-opacity"] = 0.5;
    });
    console.log(JSON.stringify(geojson, null, "  "));
  })
  .catch(function(error) {
    console.log(error);
  });

以前は shapefile.read(shp,"shift_jis",function(error,geojson){...}) のようにコールバック関数を使用するスタイルだったのですが、 Promise を使う形に変更されました。

また、API 自体も shapefile.read(shp,dbf,option) のように、第一引数に shp、続いて dbf (省略可能、shp のパスから補完される)、最後に option (省略可能) を指定するように変更されています。

実際に実行するには以下のように。

$ node main.js N03-20150101_02_GML/N03-15_02_150101.shp > out.geojson

なお、read は入力を一括変換するので比較的小さなデータの処理に向いています。大きなデータについては逐次処理をする open という API も提供されています。

3.ブラウザでの使用

以前は node.js で動作することを前提としたモジュールだったのですが、ブラウザでも動作するようになりました。Drag & Drop API や XMLHttpRequest を介して取得した Shapefile を直接ブラウザで GeoJSON に変換することも可能になったみたいです。

Web 上にある Shapefile を取得して GeoJSON に変換してコンソールに出力する例がこちら。

index.html

<!DOCTYPE html>
<html>

<head>
  <script src="https://unpkg.com/shapefile@0.5.7"></script>
</head>

<body>
  <script>
    shapefile
      .read("https://cdn.rawgit.com/mbostock/shapefile/master/test/points.shp")
      .then(geojson => {
        console.log(geojson);
      })
      .catch(error => console.error(error.stack));
  </script>
</body>

</html>

shapefile.read(shp,dbf,option) の shp にはファイルパス以外にも URL やバイナリ、ストリームなどを指定することもでき、この例では shp として与えられた URL をもとに shp と dbf が XMLHttpRequest でネットワークから取得され、ブラウザ上で GeoJSON に変換されます。

4. まとめ

npm の shapefile ライブラリの更新ポイントを紹介しました。対応文字コードの改善や Promise を使った API のリファインなど、 Node.js から利用しやすくなったと思います。

ブラウザで Shapefile を扱うシーンはあんまり考えたくないですが、覚えておくといつか役に立つ日がくるかもしれません。

12
11
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
12
11