geojson から topojson への変換
geojsonからtopojsonへの変換はググったらたくさん出てきてどれもnodejsのパッケージのtopojsonを使ったものが多かった。今回もそれを使います。
$ npm i -g topojson $ geo2topo -q 1e6 railroad=N02-15_RailroadSection.json > N02-15_RailroadSection.topojson
-q 1e6
というオプションが変換時に大切なものらしく ほぼ常時つけた方がよいらしい
railroadとはtopojsonでのオブジェクト名になるらしい。
D3.jsによるtopojsonの描画
変換したtopojsonファイルを描画していきます。
使うライブラリはみんな大好きD3です。
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <meta charset="utf-8" /> <title></title> <style> </style> </head> <body> <h1>Rail Road Test</h1> <script src="//d3js.org/d3.v3.min.js" charset="utf-8"></script> <script src="//d3js.org/topojson.v0.min.js" charset="utf-8"></script> <script src="test.js"></script> </body>
次にtest.jsについて
var width = 800; var height = 800; var svg = d3.select("body") .append("svg") .attr("width", width) .attr("height", height); d3.json("rail_road.topojson", function(error, topo){ var data = topojson.object(topo, topo.objects.railroad) var projection = d3.geo.mercator() .center(d3.geo.centroid(data)) .scale(1200) .translate([width/2, height/2]) var path = d3.geo.path().projection(projection); svg.selectAll("path") .data(data.geometries) .enter() .append("path") .attr("d", path); });
dataの受け渡しの際にさっき設定したオブジェクト名"railroad"を指定して行っています。
上記のhtmlをブラウザで表示すると
とまあわかりにくい
しかし描画できてるっぽいので今日はここまで!
次はこのsvg要素をオーバーレイとして、leaflet.jsなどを使い地図上に鉄道データをのせていきたいとおもいます。