<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Love web applications &#187; TopoJSON</title>
	<atom:link href="http://blog.hitsuji.me/tag/topojson/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.hitsuji.me</link>
	<description>Webアプリつくるの楽しい！つくるネタ、使うネタ、あとは雑談です。</description>
	<lastBuildDate>Sun, 25 Jan 2015 12:49:45 +0000</lastBuildDate>
	<language>ja</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=4.1.41</generator>
	<item>
		<title>横浜市地図に数値Dataラベルを貼る</title>
		<link>http://blog.hitsuji.me/add-labels-of-population-values-to-yokohama-city-map/</link>
		<comments>http://blog.hitsuji.me/add-labels-of-population-values-to-yokohama-city-map/#comments</comments>
		<pubDate>Thu, 31 Jul 2014 11:56:37 +0000</pubDate>
		<dc:creator><![CDATA[kapibarawebmaster1515]]></dc:creator>
				<category><![CDATA[可視化]]></category>
		<category><![CDATA[D3.js]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[map]]></category>
		<category><![CDATA[TopoJSON]]></category>

		<guid isPermaLink="false">http://blog.hitsuji.me/?p=174</guid>
		<description><![CDATA[今日は地図の方を進めようと思います。前回記事「横浜市地図を人口に応じて色塗りする」で描いた地図に、区名ラベルだけでなく数値のラベルも添付できるようにしたいと思います。 &#160; &#160; ポリ・・・<a class="readon" href="http://blog.hitsuji.me/add-labels-of-population-values-to-yokohama-city-map/">続きを読む</a>]]></description>
				<content:encoded><![CDATA[<p>今日は地図の方を進めようと思います。<a title="横浜市地図を人口に応じて色塗りする" href="http://blog.hitsuji.me/show-yokohama-city-map-filled-with-colors-according-to-population/">前回記事「横浜市地図を人口に応じて色塗りする」</a>で描いた地図に、区名ラベルだけでなく数値のラベルも添付できるようにしたいと思います。</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<h3>ポリゴンの中央にラベルを２行を貼付ける</h3>
<p>区毎のポリゴンの中央にラベルが２行くるように位置を調整しつつ、ラベルを貼っていきます。</p>
<p>実際に描いた地図が次の通り（画像をクリックすると地図ページに飛びます）。</p>
<p><a href="http://static.hitsuji.me/map-yokohama09/"><img class="alignnone size-medium_for_2x wp-image-177" src="http://blog.hitsuji.me/app/wp-content/uploads/2014/07/yokohama_map09-436x600.png" alt="yokohama_map09" width="218" height="300" /></a></p>
<p>&nbsp;</p>
<p>やっていることはカンタン。テキストラベルのtransform属性で指定する高さ方向の位置について、上の行は-0.5行、下の行は+0.5行だけシフトさせているだけです。行間は予め決めてあります（labelLineHight）。</p>
<p>&nbsp;</p>
<p>ちなみに・・・<br />
縦方向の座標は下向きが正なので、通常の感覚と逆方向になります。上方向への移動がマイナス，下がプラスですね。</p>
<p>&nbsp;</p>
<p>ソースコードは次の通り。</p>
<h6>index.html</h6>
<script src="https://gist.github.com/b22bcf139ef5c3bed2e6.js"></script><noscript><pre><code class="language-html html">&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;ja&quot;&gt;
&lt;head&gt;
&lt;meta charset=&quot;utf-8&quot;&gt;
&lt;script src=&quot;http://d3js.org/d3.v3.min.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;http://d3js.org/topojson.v0.min.js&quot;&gt;&lt;/script&gt;
&lt;style type=&quot;text/css&quot;&gt;
h1 {
    font-size: 16px;
}
svg {
    border: 1px solid #aaaaaa;
}
.subunit-boundary {
  fill: none;
  stroke: #777;
  stroke-dasharray: 2,2;
  stroke-linejoin: round;
}
.cityname-label {
    fill-opacity: .5;
    font-size: 8px;
    font-weight: 300;     
    text-anchor: middle;
    display: none;
}
.stat-label {
    fill-opacity: .5;
    font-size: 8px;
    font-weight: 300;
    text-anchor: middle;
    display: none;
}
&lt;/style&gt;
&lt;title&gt;Yokohama city map&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h1&gt;Yokohama city map&lt;/h1&gt;
&lt;div id=&quot;map&quot;&gt;&lt;/div&gt;

&lt;script type=&quot;text/javascript&quot;&gt;
    
    // file読み込み制御用
    var readTopofileDone = false;
    var readAttrfileDone = false;
    // filedata格納変数
    var topodata;
    var attrdata;
    
    var map_width = 500;
    var map_height = 650;
    var svg;
    
    function readTopofile(json) {
        topodata = json;
        readTopofileDone = true;
    }
    function readAttrfile(json) {
        attrdata = json;
        readAttrfileDone = true;
    }
    
    d3.json(&quot;yokohama_topo_out.json&quot;, function(error, json) {
        if(error) return console.warn(error);
            readTopofile(json);
            if (readTopofileDone &amp;&amp; readAttrfileDone) {
                main(topodata, attrdata);
            }
        });
    
    d3.json(&quot;yokohama_codes_and_stat.json&quot;, function(error, json) {
        if(error) return console.warn(error);
            readAttrfile(json);
            if (readTopofileDone &amp;&amp; readAttrfileDone) {
                main(topodata, attrdata);
            }
        });
    
    function main(topo, attr) {
        
        var labelLineHight = 16;
        // 属性情報を入れ直すためのHash Table
        var attrHash = new Object();
        
        // attr情報を、IDをkeyとするhash-tableに変換する
        // idをKeyとしたhashテーブル＆property毎のhashテーブルを作成する
        attr.forEach(function(e){
            attrHash[e.cityid]=e;
        });
        
        // 人口の最大値と最小値を求めておく
        // --全年齢人口データのみを入れた配列を作成する
        var elements = [];
        var target_key = &quot;ttl&quot;;
        attr.forEach(function(e){
            elements.push(e[target_key]);
        });
        // -- maxとminをとる
        var target_max = Math.max.apply(null, elements);
        var target_min = Math.min.apply(null, elements);
        
         // svgを追加
        svg = d3.select(&quot;body #map&quot;).append(&quot;svg&quot;)
                .attr(&quot;width&quot;, map_width)
                .attr(&quot;height&quot;, map_height);
        
        // 横浜市のmapを描画する
        var yokohama = topojson.object(topo, topo.objects.yokohama);
        console.log(yokohama);
        
        // 横浜市を中心に指定したメルカトル図法で10万分の1で描画する
        var projection = d3.geo.mercator()
                .center([139.59,35.45])
                .scale(100000)
                .translate([map_width / 2, map_height / 2]);
        
        // pathを作成する
        var path = d3.geo.path().projection(projection);
        svg.append(&quot;path&quot;)
          .datum(yokohama)
          .attr(&quot;d&quot;, path);
        
        // classを指定する
        svg.selectAll(&quot;.yokohama&quot;)
            .data(yokohama.geometries)
        .enter().append(&quot;path&quot;)
            .attr(&quot;class&quot;, function(d) {
                return &quot;yokohama &quot; + d.properties.name;
                })
            .attr(&quot;d&quot;, path);
        
        // 色を塗る
        var areaGrad = d3.scale.linear()
                        .domain([target_min, target_max])
                        .range([&quot;#bee59e&quot;, &quot;#349946&quot;]);
        svg.selectAll(&quot;path&quot;).attr(&quot;fill&quot;, &quot;#bee59e&quot;);
        for (var k in attrHash) {
            svg.selectAll(&quot;.&quot;+k).attr(&quot;fill&quot;, areaGrad(attrHash[k][target_key]));
        }
        
        // 内部境界に線を引く
        svg.append(&quot;path&quot;)
           .datum(topojson.mesh(topo, topo.objects.yokohama, function(a, b) { return a !== b; }))
           .attr(&quot;d&quot;, path)
           .attr(&quot;class&quot;, &quot;subunit-boundary&quot;);
        
        // 区コードのラベル貼り
        var city_labels = new Array();
        svg.selectAll(&quot;.cityname-label&quot;)
            .data(yokohama.geometries)
          .enter()
            .append(&quot;text&quot;)
                .attr(&quot;class&quot;, function(d) {
                    if(!(city_labels.indexOf(d.properties.name) &gt; -1)) {
                        city_labels.push(d.properties.name);
                    }
                    return &quot;cityname-label &quot;+d.properties.name; // class名にidを付与
                    })
                .attr(&quot;transform&quot;, function(d) {
                    // 文字をpath中央から、文字高さ1/2分高い位置に貼る
                    var pos = path.centroid(d);
                    pos[1] -= labelLineHight / 2;
                    return &quot;translate(&quot; + pos + &quot;)&quot;;
                })
                .attr(&quot;dy&quot;, &quot;.35em&quot;)
                .text(function(d) {
                    return attrHash[d.properties.name].name;
                });
        
        // 値ラベル貼り
        svg.selectAll(&quot;.stat-label&quot;)
            .data(yokohama.geometries)
          .enter()
            .append(&quot;text&quot;)
                .attr(&quot;class&quot;, function(d) {
                    if(!(city_labels.indexOf(d.properties.name) &gt; -1)) {
                        city_labels.push(d.properties.name);
                    }
                    return &quot;stat-label &quot;+d.properties.name; // class名にidを付与
                    })
                .attr(&quot;transform&quot;, function(d) {
                    // 文字をpath中央から、文字高さ1/2分高い位置に貼る
                    var pos = path.centroid(d);
                    pos[1] += labelLineHight / 2;
                    return &quot;translate(&quot; + pos + &quot;)&quot;;
                })
                .attr(&quot;dy&quot;, &quot;.35em&quot;)
                .text(function(d) {
                    return attrHash[d.properties.name][target_key];
                });
        
        // 各最初のエリアのみラベルを表示する
        for (var i in city_labels) {
            svg.select(&quot;.cityname-label.&quot;+city_labels[i]).style(&quot;display&quot;, &quot;block&quot;);
            svg.select(&quot;.stat-label.&quot;+city_labels[i]).style(&quot;display&quot;, &quot;block&quot;);
        }
        
    }
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;</code></pre></noscript>
<p>&nbsp;</p>
<p>動けばよし！という感じのコードになってしまいましたが、数値ラベルも合わせて貼れました♪</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>ただ、濃い緑の背景の箇所は黒いテキストラベルが見づらいですね。背景が濃い場合は文字色を白にすると良いのではないでしょうか。</p>
<p>という訳で、次はこの問題を解決すべく、ラベルの色制御をしてみようと思います。</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.hitsuji.me/add-labels-of-population-values-to-yokohama-city-map/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>横浜市地図を人口に応じて色塗りする</title>
		<link>http://blog.hitsuji.me/show-yokohama-city-map-filled-with-colors-according-to-population/</link>
		<comments>http://blog.hitsuji.me/show-yokohama-city-map-filled-with-colors-according-to-population/#comments</comments>
		<pubDate>Fri, 25 Jul 2014 02:23:00 +0000</pubDate>
		<dc:creator><![CDATA[kapibarawebmaster1515]]></dc:creator>
				<category><![CDATA[可視化]]></category>
		<category><![CDATA[D3.js]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[map]]></category>
		<category><![CDATA[TopoJSON]]></category>

		<guid isPermaLink="false">http://blog.hitsuji.me/?p=141</guid>
		<description><![CDATA[こんにちは。昨夜の大雨から一転して真夏の気候で大変ですね。外出時には日傘必須です^^; &#160; 地図を人口の大小に応じて色分けする さて、前回の記事「JSONファイルをCSVファイルに変換する」・・・<a class="readon" href="http://blog.hitsuji.me/show-yokohama-city-map-filled-with-colors-according-to-population/">続きを読む</a>]]></description>
				<content:encoded><![CDATA[<p>こんにちは。昨夜の大雨から一転して真夏の気候で大変ですね。外出時には日傘必須です^^;</p>
<p>&nbsp;</p>
<h3>地図を人口の大小に応じて色分けする</h3>
<p>さて、前回の記事「<a title="JSONファイルをCSVファイルに変換する" href="http://blog.hitsuji.me/read-json-conv-2-dimension-list-and-write-it-to-csv/">JSONファイルをCSVファイルに変換する</a>」で作成したJSONファイルを使って、横浜市地図を改めて描きます。行政区毎の人口数の大小に応じて、地図を色塗りします。</p>
<p>&nbsp;</p>
<h4>地図を描画する</h4>
<p>早速完成した地図です♪画像をクリックしてくださいね^^</p>
<p><a href="http://static.hitsuji.me/map-yokohama08/"><img class="alignnone size-medium_for_2x wp-image-142" src="http://blog.hitsuji.me/app/wp-content/uploads/2014/07/yokohama_map08-440x600.png" alt="yokohama_map08" width="220" height="300" /></a></p>
<p>&nbsp;</p>
<p>人口が多い区は濃く、少ない区は薄い色に指定してみました。</p>
<p>&nbsp;</p>
<p>元のソースコードはこちら。</p>
<h6>index.html</h6>
<script src="https://gist.github.com/41e2745f0736ae25bc31.js"></script><noscript><pre><code class="language-html html">&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;ja&quot;&gt;
&lt;head&gt;
&lt;meta charset=&quot;utf-8&quot;&gt;
&lt;script src=&quot;http://d3js.org/d3.v3.min.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;http://d3js.org/topojson.v0.min.js&quot;&gt;&lt;/script&gt;
&lt;style type=&quot;text/css&quot;&gt;
h1 {
    font-size: 16px;
}
svg {
    border: 1px solid #aaaaaa;
}
.subunit-boundary {
  fill: none;
  stroke: #777;
  stroke-dasharray: 2,2;
  stroke-linejoin: round;
}
.cityname-label {
    fill-opacity: .5;
    font-size: 8px;
    font-weight: 300;     
    text-anchor: middle;
    display: none;
}
&lt;/style&gt;
&lt;title&gt;Yokohama city map&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h1&gt;Yokohama city map&lt;/h1&gt;
&lt;div id=&quot;map&quot;&gt;&lt;/div&gt;

&lt;script type=&quot;text/javascript&quot;&gt;
    
    // file読み込み制御用
    var readTopofileDone = false;
    var readAttrfileDone = false;
    // filedata格納変数
    var topodata;
    var attrdata;
    
    var map_width = 500;
    var map_height = 650;
    var svg;
    
    function readTopofile(json) {
        topodata = json;
        readTopofileDone = true;
    }
    function readAttrfile(json) {
        attrdata = json;
        readAttrfileDone = true;
    }
    
    d3.json(&quot;yokohama_topo_out.json&quot;, function(error, json) {
        if(error) return console.warn(error);
            readTopofile(json);
            if (readTopofileDone &amp;&amp; readAttrfileDone) {
                main(topodata, attrdata);
            }
        });
    
    d3.json(&quot;yokohama_codes_and_stat.json&quot;, function(error, json) {
        if(error) return console.warn(error);
            readAttrfile(json);
            if (readTopofileDone &amp;&amp; readAttrfileDone) {
                main(topodata, attrdata);
            }
        });
    
    function main(topo, attr) {
        
        var labelLineHight = 16;
        // 属性情報を入れ直すためのHash Table
        var attrHash = new Object();
        
        // attr情報を、IDをkeyとするhash-tableに変換する
        // idをKeyとしたhashテーブル＆property毎のhashテーブルを作成する
        attr.forEach(function(e){
            attrHash[e.cityid]=e;
        });
        
        // 人口の最大値と最小値を求めておく
        // --全年齢人口データのみを入れた配列を作成する
        var elements = [];
        var target_key = &quot;ttl&quot;;
        attr.forEach(function(e){
            elements.push(e[target_key]);
        });
        // -- maxとminをとる
        var target_max = Math.max.apply(null, elements);
        var target_min = Math.min.apply(null, elements);
        
         // svgを追加
        svg = d3.select(&quot;body #map&quot;).append(&quot;svg&quot;)
                .attr(&quot;width&quot;, map_width)
                .attr(&quot;height&quot;, map_height);
        
        // 横浜市のmapを描画する
        var yokohama = topojson.object(topo, topo.objects.yokohama);
        console.log(yokohama);
        
        // 横浜市を中心に指定したメルカトル図法で10万分の1で描画する
        var projection = d3.geo.mercator()
                .center([139.59,35.45])
                .scale(100000)
                .translate([map_width / 2, map_height / 2]);
        
        // pathを作成する
        var path = d3.geo.path().projection(projection);
        svg.append(&quot;path&quot;)
          .datum(yokohama)
          .attr(&quot;d&quot;, path);
        
        // classを指定する
        svg.selectAll(&quot;.yokohama&quot;)
            .data(yokohama.geometries)
        .enter().append(&quot;path&quot;)
            .attr(&quot;class&quot;, function(d) {
                return &quot;yokohama &quot; + d.properties.name;
                })
            .attr(&quot;d&quot;, path);
        
        // 色を塗る
        var areaGrad = d3.scale.linear()
                        .domain([target_min, target_max])
                        .range([&quot;#bee59e&quot;, &quot;#349946&quot;]);
        svg.selectAll(&quot;path&quot;).attr(&quot;fill&quot;, &quot;#bee59e&quot;);
        for (var k in attrHash) {
            svg.selectAll(&quot;.&quot;+k).attr(&quot;fill&quot;, areaGrad(attrHash[k][target_key]));
        }
        
        // 内部境界に線を引く
        svg.append(&quot;path&quot;)
           .datum(topojson.mesh(topo, topo.objects.yokohama, function(a, b) { return a !== b; }))
           .attr(&quot;d&quot;, path)
           .attr(&quot;class&quot;, &quot;subunit-boundary&quot;);
        
        // 区コードのラベル貼り
        var city_labels = new Array();
        svg.selectAll(&quot;.cityname-label&quot;)
            .data(yokohama.geometries)
          .enter()
            .append(&quot;text&quot;)
                .attr(&quot;class&quot;, function(d) {
                    if(!(city_labels.indexOf(d.properties.name) &gt; -1)) {
                        city_labels.push(d.properties.name);
                    }
                    return &quot;cityname-label &quot;+d.properties.name; /* class名にidを付与 */
                    })
                .attr(&quot;transform&quot;, function(d) {
                    return &quot;translate(&quot; + path.centroid(d) + &quot;)&quot;;
                })
                .attr(&quot;dy&quot;, &quot;.35em&quot;)
                .text(function(d) {
                    return attrHash[d.properties.name].name;
                });
        
        // 各最初のエリアのみラベルを表示する
        for (var i in city_labels) {
            svg.select(&quot;.cityname-label.&quot;+city_labels[i]).style(&quot;display&quot;, &quot;block&quot;);
        }
        
    }
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;</code></pre></noscript>
<p>&nbsp;</p>
<p>L.84-93で、区毎の人口数の最大値と最小値を計算しています。</p>
<p><em><span style="color: #808080;">冗長過ぎるコードなので、すっきり直したいですが。</span></em></p>
<p>&nbsp;</p>
<p>L.116-で、各区領域にclass属性を指定しています。</p>
<p>&nbsp;</p>
<p>続いてL.126-で色塗りしています。</p>
<p>D3.jsの機能を使って、色を人口に応じて求める関数を作成します</p>
<pre class="command">areaGrad = d3.scale.linear().domain([target_min, target_max]).range(["#bee59e", "#349946"]);</pre>
<p>d3.scale.linear()は、リニアに補間した結果を返す関数を作成するもので、f = d3.scale.linear()domain([x1, x2]).range([y1, y2])とすると、f(x)は下図のように補間した値yを返してくれます。</p>
<p><img class="alignnone size-large_for_2x wp-image-144" src="http://blog.hitsuji.me/app/wp-content/uploads/2014/07/d3_scale_linear.png" alt="d3_scale_linear" width="600" height="400" /></p>
<p>&nbsp;</p>
<p>さらに、range()には16進数RGB colorも指定できるという優れもので、range([薄い緑, 濃い緑])を指定しました。</p>
<p>domainには、先ほど求めた人口の最小値＆最大値を指定してありますので、</p>
<p><img class="alignnone size-large_for_2x wp-image-145" src="http://blog.hitsuji.me/app/wp-content/uploads/2014/07/d3_scale_linear_ex_2x.png" alt="d3_scale_linear_ex_2x" width="600" height="400" /></p>
<p>&nbsp;</p>
<p>という感じで、L.131でfill指定する色を返してくれます。</p>
<p>&nbsp;</p>
<p>色塗り完成です♪</p>
<p>次回は、人口の数値自体を地図に書き入れる処理を追加したいと思います。</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.hitsuji.me/show-yokohama-city-map-filled-with-colors-according-to-population/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>横浜市地図に区名を表示する</title>
		<link>http://blog.hitsuji.me/show-yokohama-city-map-divided-into-administrative-divisions-with-its-each/</link>
		<comments>http://blog.hitsuji.me/show-yokohama-city-map-divided-into-administrative-divisions-with-its-each/#comments</comments>
		<pubDate>Sat, 28 Jun 2014 05:41:17 +0000</pubDate>
		<dc:creator><![CDATA[kapibarawebmaster1515]]></dc:creator>
				<category><![CDATA[可視化]]></category>
		<category><![CDATA[D3.js]]></category>
		<category><![CDATA[map]]></category>
		<category><![CDATA[TopoJSON]]></category>

		<guid isPermaLink="false">http://blog.hitsuji.me/?p=103</guid>
		<description><![CDATA[こんにちは。梅雨で毎日ジメジメしていますが、気分だけは元気にブログを更新しようと思います。 &#160; 横浜市地図に日本語区名を表示する さて、今日でようやく横浜市地図に区名ラベルを表示できます。以・・・<a class="readon" href="http://blog.hitsuji.me/show-yokohama-city-map-divided-into-administrative-divisions-with-its-each/">続きを読む</a>]]></description>
				<content:encoded><![CDATA[<p>こんにちは。梅雨で毎日ジメジメしていますが、気分だけは元気にブログを更新しようと思います。</p>
<p>&nbsp;</p>
<h3>横浜市地図に日本語区名を表示する</h3>
<p>さて、今日でようやく横浜市地図に区名ラベルを表示できます。以前書いた記事「<a title="横浜市地図の各区に１つだけラベル表示する" href="http://blog.hitsuji.me/show-yokohama-city-map-with-label-of-unique-id/">横浜市地図の各区に１つだけラベル表示する</a>」で紹介したコードを、前回の記事「<a title="2つのJSONファイルを読み込む" href="http://blog.hitsuji.me/read-2-jsons-using-d3-js/">2つのJSONファイルを読み込む</a>」のコードでModifyしました。</p>
<p>&nbsp;</p>
<h4>横浜市地図の完成です♪</h4>
<p>下のような地図が出来上がりました。画像をクリックすると、地図ページに飛びます。</p>
<p><a href="http://static.hitsuji.me/map-yokohama07/"><img class="alignnone wp-image-104 size-medium_for_2x" src="http://blog.hitsuji.me/app/wp-content/uploads/2014/06/yokohama_map07-442x600.png" alt="yokohama_map07" width="221" height="300" /></a></p>
<p>&nbsp;</p>
<p>コードは次の通りです。</p>
<h6>index.html</h6>
<script src="https://gist.github.com/f5024f3d9db4536887a9.js"></script><noscript><pre><code class="language-html html">&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;ja&quot;&gt;
&lt;head&gt;
&lt;meta charset=&quot;utf-8&quot;&gt;
&lt;script src=&quot;http://d3js.org/d3.v3.min.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;http://d3js.org/topojson.v0.min.js&quot;&gt;&lt;/script&gt;
&lt;style type=&quot;text/css&quot;&gt;
h1 {
    font-size: 16px;
}
svg {
    border: 1px solid #aaaaaa;
}
.subunit-boundary {
  fill: none;
  stroke: #777;
  stroke-dasharray: 2,2;
  stroke-linejoin: round;
}
.cityname-label {
    fill-opacity: .5;
    font-size: 8px;
    font-weight: 300;     
    text-anchor: middle;
    display: none;
}
&lt;/style&gt;
&lt;title&gt;Yokohama city map&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h1&gt;Yokohama city map&lt;/h1&gt;
&lt;div id=&quot;map&quot;&gt;&lt;/div&gt;

&lt;script type=&quot;text/javascript&quot;&gt;
    
    // file読み込み制御用
    var readTopofileDone = false;
    var readAttrfileDone = false;
    // filedata格納変数
    var topodata;
    var attrdata;
    
    var map_width = 500;
    var map_height = 650;
    var svg;
    
    function readTopofile(json) {
        topodata = json;
        readTopofileDone = true;
    }
    function readAttrfile(json) {
        attrdata = json;
        readAttrfileDone = true;
    }
    
    d3.json(&quot;yokohama_topo_out.json&quot;, function(error, json) {
        if(error) return console.warn(error);
            readTopofile(json);
            if (readTopofileDone &amp;&amp; readAttrfileDone) {
                main(topodata, attrdata);
            }
        });
    
    d3.json(&quot;yokohama_codes.json&quot;, function(error, json) {
        if(error) return console.warn(error);
            readAttrfile(json);
            if (readTopofileDone &amp;&amp; readAttrfileDone) {
                main(topodata, attrdata);
            }
        });
    
    function main(topo, attr) {
        
        var labelLineHight = 16;
        // 属性情報を入れ直すためのHash Table
        var attrHash = new Object();
        
        // attr情報を、IDをkeyとするhash-tableに変換する
        // idをKeyとしたhashテーブル＆property毎のhashテーブルを作成する
        attr.forEach(function(e){
            attrHash[e.cityid]=e;
        });
        
         // svgを追加
        svg = d3.select(&quot;body #map&quot;).append(&quot;svg&quot;)
                .attr(&quot;width&quot;, map_width)
                .attr(&quot;height&quot;, map_height);
                
        // 横浜市のmapを描画する
        var yokohama = topojson.object(topo, topo.objects.yokohama);
        console.log(yokohama);
        
        // 横浜市を中心に指定したメルカトル図法で10万分の1で描画する
        var projection = d3.geo.mercator()
                .center([139.59,35.45])
                .scale(100000)
                .translate([map_width / 2, map_height / 2]);
        
        // pathを作成する
        var path = d3.geo.path().projection(projection);
        svg.append(&quot;path&quot;)
          .datum(yokohama)
          .attr(&quot;d&quot;, path);
        
        // 色を塗る
        svg.selectAll(&quot;path&quot;).attr(&quot;fill&quot;, &quot;#bee59e&quot;);
        
        // 内部境界に線を引く
        svg.append(&quot;path&quot;)
           .datum(topojson.mesh(topo, topo.objects.yokohama, function(a, b) { return a !== b; }))
           .attr(&quot;d&quot;, path)
           .attr(&quot;class&quot;, &quot;subunit-boundary&quot;);
        
        // 区コードのラベル貼り
        var city_labels = new Array();
        svg.selectAll(&quot;.cityname-label&quot;)
            .data(yokohama.geometries)
          .enter()
            .append(&quot;text&quot;)
                .attr(&quot;class&quot;, function(d) {
                    if(!(city_labels.indexOf(d.properties.name) &gt; -1)) {
                        city_labels.push(d.properties.name);
                    }
                    return &quot;cityname-label &quot;+d.properties.name; /* class名にidを付与 */
                    })
                .attr(&quot;transform&quot;, function(d) {
                    return &quot;translate(&quot; + path.centroid(d) + &quot;)&quot;;
                })
                .attr(&quot;dy&quot;, &quot;.35em&quot;)
                .text(function(d) {
                    return attrHash[d.properties.name].name;
                });
        
        // 各最初のエリアのみラベルを表示する
        for (var i in city_labels) {
            svg.select(&quot;.cityname-label.&quot;+city_labels[i]).style(&quot;display&quot;, &quot;block&quot;);
        }
        
    }
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;</code></pre></noscript>
<p>&nbsp;</p>
<p>変更点は２カ所だけです。</p>
<h5>属性データの構造を、&#8221;id&#8221;+団体コードをキーとするHashに変換する</h5>
<p>JSONファイルから読み込んだデータ配列は、そのままだと使いづらいので、団体コードをキーとするHashテーブル（attr =&gt; attrHash）に組み直します。</p>
<p>&nbsp;</p>
<h5>ラベルを区名に変更する</h5>
<p>区名を貼るコードについて、d.properties.nameの箇所を、attrHash[d.properties.name].nameに書き換えます。</p>
<p>&nbsp;</p>
<p>やっと普通の横浜市地図が描けました（笑）。</p>
<p>次は、横浜市の人口データの表示に進もうと思います。</p>
<p>それではまた♥︎</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.hitsuji.me/show-yokohama-city-map-divided-into-administrative-divisions-with-its-each/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>2つのJSONファイルを読み込む</title>
		<link>http://blog.hitsuji.me/read-2-jsons-using-d3-js/</link>
		<comments>http://blog.hitsuji.me/read-2-jsons-using-d3-js/#comments</comments>
		<pubDate>Thu, 19 Jun 2014 11:51:53 +0000</pubDate>
		<dc:creator><![CDATA[kapibarawebmaster1515]]></dc:creator>
				<category><![CDATA[可視化]]></category>
		<category><![CDATA[D3.js]]></category>
		<category><![CDATA[TopoJSON]]></category>

		<guid isPermaLink="false">http://blog.hitsuji.me/?p=98</guid>
		<description><![CDATA[こんばんは。今夜も前回の記事「区名と行政団体コードを書き並べたCSVからJSONファイルを作成する」の続きで、せっせと地図を描き進めようと思います。 &#160; D3.jsのJSON読み込みは非同期・・・<a class="readon" href="http://blog.hitsuji.me/read-2-jsons-using-d3-js/">続きを読む</a>]]></description>
				<content:encoded><![CDATA[<p>こんばんは。今夜も<a title="区名と行政団体コードを書き並べたCSVからJSONファイルを作成する" href="http://blog.hitsuji.me/convert-csv-listing-words-name-and-their-codes-to-json/">前回の記事「区名と行政団体コードを書き並べたCSVからJSONファイルを作成する」</a>の続きで、せっせと地図を描き進めようと思います。</p>
<p>&nbsp;</p>
<h4>D3.jsのJSON読み込みは非同期処理</h4>
<p>D3.jsでJSONファイルを読み込むには、</p>
<pre class="command">d3.js(filename)</pre>
<p>という関数が用意されており、とても簡単に利用することができます。</p>
<p>&nbsp;</p>
<p>しかし、２つのファイルを読み込むときは若干面倒です。２ファイル読み込みがそれぞれ独立している処理なので、両方のファイルが読み込まれるのを待ってから、main処理を開始しなければなりません。</p>
<p>&nbsp;</p>
<h4>制御用フラグを使う</h4>
<p>２ファイル両方の読み込みが終わるのを待つ必要があります。そのため、制御用に各ファイルの読み込み完了フラグを用意しておき、ファイル読み込み完了した後でフラグを立てるようにします。そして、両方のフラグが立った時に初めてmain()を呼び出します。</p>
<p>&nbsp;</p>
<p>こんな感じです。</p>
<h6>index.html (scriptの一部)</h6>
<script src="https://gist.github.com/fc88e660c80c6eae78be.js"></script><noscript><pre><code class="language-javascript javascript">// file読み込み制御用
var readTopofileDone = false;
var readAttrfileDone = false;
// filedata格納変数
var topodata;
var attrdata;

var map_width = 500;
var map_height = 650;
var svg;

function readTopofile(json) {
    topodata = json;
    readTopofileDone = true;
}
function readAttrfile(json) {
    attrdata = json;
    readAttrfileDone = true;
}

d3.json(&quot;yokohama_topo_out.json&quot;, function(error, json) {
    if(error) return console.warn(error);
        readTopofile(json);
        if (readTopofileDone &amp;&amp; readAttrfileDone) {
            main(topodata, attrdata);
        }
    });

d3.json(&quot;yokohama_codes.json&quot;, function(error, json) {
    if(error) return console.warn(error);
        readAttrfile(json);
        if (readTopofileDone &amp;&amp; readAttrfileDone) {
            main(topodata, attrdata);
        }
    });

function main(topo, attr) {
    // break
}</code></pre></noscript>
<p>&nbsp;</p>
<p>main関数内でbreakしてみました。</p>
<p><img class="alignnone size-large_for_2x wp-image-99" src="http://blog.hitsuji.me/app/wp-content/uploads/2014/06/break-1200x720.png" alt="break" width="600" height="360" /></p>
<p>&nbsp;</p>
<p>ちょっと見づらいですが、attrとtopoの両方の変数がちゃんと見えるのを確認しました♥︎</p>
<p>&nbsp;</p>
<p>今日はここまで。</p>
<p>次回は属性情報（区名）を使って、地図上のラベルをコードから名前に変えます！</p>
<p>それでは〜</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.hitsuji.me/read-2-jsons-using-d3-js/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>横浜市地図の各区に１つだけラベル表示する</title>
		<link>http://blog.hitsuji.me/show-yokohama-city-map-with-label-of-unique-id/</link>
		<comments>http://blog.hitsuji.me/show-yokohama-city-map-with-label-of-unique-id/#comments</comments>
		<pubDate>Thu, 12 Jun 2014 01:52:34 +0000</pubDate>
		<dc:creator><![CDATA[kapibarawebmaster1515]]></dc:creator>
				<category><![CDATA[可視化]]></category>
		<category><![CDATA[D3.js]]></category>
		<category><![CDATA[map]]></category>
		<category><![CDATA[TopoJSON]]></category>

		<guid isPermaLink="false">http://blog.hitsuji.me/?p=86</guid>
		<description><![CDATA[こんにちは。今日は、前回記事「区名を英数字コードに置換する」でTopoJSONファイルの中の区名をID番号に書き換えたものを使って、再度横浜市地図を表示してみます。 &#160; 区名の代わりに行政団・・・<a class="readon" href="http://blog.hitsuji.me/show-yokohama-city-map-with-label-of-unique-id/">続きを読む</a>]]></description>
				<content:encoded><![CDATA[<p>こんにちは。今日は、<a title="区名を英数字コードに置換する" href="http://blog.hitsuji.me/replacement-from-word-name-to-its-code/">前回記事「区名を英数字コードに置換する」</a>でTopoJSONファイルの中の区名をID番号に書き換えたものを使って、再度横浜市地図を表示してみます。</p>
<p>&nbsp;</p>
<h4>区名の代わりに行政団体コードをラベル表示する</h4>
<p><a title="地図に区名を表示する" href="http://blog.hitsuji.me/show-words-name-on-yokohama-city-map/">前々回の記事「地図に区名を表示する」</a>で利用したindex.htmlをそのまま流用して、地図表示してみます。（読み込むTopoJSONファイルを、区名=&gt;コードに置換したものに変えるだけです）</p>
<p><a href="http://static.hitsuji.me/map-yokohama04/"><img class="alignnone size-medium_for_2x wp-image-87" src="http://blog.hitsuji.me/app/wp-content/uploads/2014/06/yokohama_map04-439x600.png" alt="yokohama_map04" width="219" height="300" /></a></p>
<p>TopoJSONファイルの区名を&#8221;id&#8221;+団体コードに書き換えたので、地図上のラベルもコードに置き換わりました。</p>
<p>&nbsp;</p>
<h4>各区１つだけラベルを表示する</h4>
<p>このままだと、前々回の記事と同様に同じ番号が重複表示されているので、修正します。</p>
<h6>index.html</h6>
<script src="https://gist.github.com/dd8d6440d6b06b6fa330.js"></script><noscript><pre><code class="language-html html">&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;ja&quot;&gt;
&lt;head&gt;
&lt;meta charset=&quot;utf-8&quot;&gt;
&lt;script src=&quot;http://d3js.org/d3.v3.min.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;http://d3js.org/topojson.v0.min.js&quot;&gt;&lt;/script&gt;
&lt;style type=&quot;text/css&quot;&gt;
h1 {
    font-size: 16px;
}
svg {
    border: 1px solid #aaaaaa;
}
.subunit-boundary {
  fill: none;
  stroke: #777;
  stroke-dasharray: 2,2;
  stroke-linejoin: round;
}
.cityname-label {
    fill-opacity: .5;
    font-size: 8px;
    font-weight: 300;     
    text-anchor: middle;
    display: none;
}
&lt;/style&gt;
&lt;title&gt;Yokohama city map&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h1&gt;Yokohama city map&lt;/h1&gt;
&lt;div id=&quot;map&quot;&gt;&lt;/div&gt;

&lt;script type=&quot;text/javascript&quot;&gt;
    var map_width = 500;
    var map_height = 650;
    var svg;
    
    d3.json(&quot;yokohama_topo_out.json&quot;, function(error, json) {
        if( !error ) {
            main(json);
        }
        return;
    });
    
    function main(topo) {
        
        var labelLineHight = 16;
         // svgを追加
        svg = d3.select(&quot;body&quot;).append(&quot;svg&quot;)
                .attr(&quot;width&quot;, map_width)
                .attr(&quot;height&quot;, map_height);
                
        // 横浜市のmapを描画する
        var yokohama = topojson.object(topo, topo.objects.yokohama);
        console.log(yokohama);
        
        // 横浜市を中心に指定したメルカトル図法で10万分の1で描画する
        var projection = d3.geo.mercator()
                .center([139.59,35.45])
                .scale(100000)
                .translate([map_width / 2, map_height / 2]);
        
        // pathを作成する
        var path = d3.geo.path().projection(projection);
        svg.append(&quot;path&quot;)
          .datum(yokohama)
          .attr(&quot;d&quot;, path);
        
        // 色を塗る
        svg.selectAll(&quot;path&quot;).attr(&quot;fill&quot;, &quot;#bee59e&quot;);
        
        // 内部境界に線を引く
        svg.append(&quot;path&quot;)
           .datum(topojson.mesh(topo, topo.objects.yokohama, function(a, b) { return a !== b; }))
           .attr(&quot;d&quot;, path)
           .attr(&quot;class&quot;, &quot;subunit-boundary&quot;);
        
        // 区コードのラベル貼り
        var city_labels = new Array();
        svg.selectAll(&quot;.cityname-label&quot;)
            .data(yokohama.geometries)
          .enter()
            .append(&quot;text&quot;)
                .attr(&quot;class&quot;, function(d) {
                    if(!(city_labels.indexOf(d.properties.name) &gt; -1)) {
                        city_labels.push(d.properties.name);
                    }
                    return &quot;cityname-label &quot;+d.properties.name; /* class名にidを付与 */
                    })
                .attr(&quot;transform&quot;, function(d) {
                    return &quot;translate(&quot; + path.centroid(d) + &quot;)&quot;;
                })
                .attr(&quot;dy&quot;, &quot;.35em&quot;)
                .text(function(d) {
                    return d.properties.name;
                });
        
        // 各最初のエリアのみラベルを表示する
        for (var i in city_labels) {
            svg.select(&quot;.cityname-label.&quot;+city_labels[i]).style(&quot;display&quot;, &quot;block&quot;);
        }
        
    }
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;</code></pre></noscript>
<p>まず区毎にラベリングしたいので、&#8221;id&#8221;+団体コードの文字列をclass属性に追加しました(L80,86-88)。そして冒頭のスタイル指定でラベルを一旦全て非表示にしておきます(L.25)。</p>
<p>地図描画処理に続いてラベル追加処理を終えた後（この時点では全てのラベルはdisplay:noneのまま）、for文で各団体コードについて１つのラベルのみdisplay:blockに書き換える処理を入れました(L.100-102)。</p>
<p><a href="http://static.hitsuji.me/map-yokohama05/"><img class="alignnone size-medium_for_2x wp-image-88" src="http://blog.hitsuji.me/app/wp-content/uploads/2014/06/yokohama_map05-440x600.png" alt="yokohama_map05" width="220" height="300" /></a></p>
<p>重複してラベル表示されていた箇所が消えました♥︎</p>
<p>でも、このままだとラベル名が団体コードってイマイチですよね。次は、これらの団体コードを再度区名に置き換えたいと思います。それではまた！</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.hitsuji.me/show-yokohama-city-map-with-label-of-unique-id/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>区名を英数字コードに置換する</title>
		<link>http://blog.hitsuji.me/replacement-from-word-name-to-its-code/</link>
		<comments>http://blog.hitsuji.me/replacement-from-word-name-to-its-code/#comments</comments>
		<pubDate>Tue, 03 Jun 2014 14:17:58 +0000</pubDate>
		<dc:creator><![CDATA[kapibarawebmaster1515]]></dc:creator>
				<category><![CDATA[可視化]]></category>
		<category><![CDATA[CSV]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[TopoJSON]]></category>

		<guid isPermaLink="false">http://blog.hitsuji.me/?p=65</guid>
		<description><![CDATA[こんばんは。この記事執筆している今は22時前なのですが、眠くて頭が溶けそうです・・・。が、眠気に負けずに記事をUpしようと思います！ &#160; 前回の振り返り：区名ラベルが重複表示される！ 前回記・・・<a class="readon" href="http://blog.hitsuji.me/replacement-from-word-name-to-its-code/">続きを読む</a>]]></description>
				<content:encoded><![CDATA[<p>こんばんは。この記事執筆している今は22時前なのですが、眠くて頭が溶けそうです・・・。が、眠気に負けずに記事をUpしようと思います！</p>
<p>&nbsp;</p>
<h3>前回の振り返り：区名ラベルが重複表示される！</h3>
<p><a title="地図に区名を表示する" href="http://blog.hitsuji.me/show-words-name-on-yokohama-city-map/">前回記事</a>の地図の続きです。</p>
<p>前回描いた地図の問題点は、複数の区名が表示されてしまうことでした。小さい島などにも全て区名が表示されると見づらいですよね。</p>
<p><a style="color: #919191;" href="http://static.hitsuji.me/map-yokohama03/"><img class="alignnone size-medium_for_2x wp-image-60" src="http://blog.hitsuji.me/app/wp-content/uploads/2014/05/yokohama_map03-443x600.png" alt="yokohama_map03" width="221" height="300" /></a></p>
<p>&nbsp;</p>
<h3>class属性を利用して表示/非表示をコントロールする</h3>
<p>重複ラベル表示を避ける方法は色々なやり方があるかと思いますが、ここでは</p>
<ul>
<li>区名を英数字のcity-codeに置き換える</li>
<li>各label要素のclass名にcity-codeを指定する</li>
<li>class名を使い、各classにつき１つのlabel要素のみ表示する</li>
</ul>
<p>という方法で行うことにします。class名に指定するには日本語だとHTMLの仕様上NGなので、各区に対応した英数字のcodeを割り振って活用します。</p>
<p>&nbsp;</p>
<h3>区名をcity-codeに置き換える</h3>
<p>TopoJSONファイルの区名を、英数字からなるcodeに置換します。割り振るcodeは連番でもよいのですが、意味がある数字を探してきました。</p>
<p>総務省<br />
<span style="color: #1c1c1c;">全国地方公共団体コード</span> <a title="総務省 全国地方公共団体コード" href="http://www.soumu.go.jp/denshijiti/code.html" target="_blank">http://www.soumu.go.jp/denshijiti/code.html</a></p>
<p>この団体コードに&#8221;id&#8221;というprefixを付けてcity-codeを作成しました。</p>
<h6>replace_words.csv</h6>
<script src="https://gist.github.com/c6be5b8daf0b564c0f10.js"></script><noscript><pre><code class="language-csv csv">港南区,id141119
鶴見区,id141011
神奈川区,id141020
西区,id141038
中区,id141046
南区,id141054
保土ケ谷区,id141062
磯子区,id141071
金沢区,id141089
港北区,id141097
戸塚区,id141101
旭区,id141127
緑区,id141135
瀬谷区,id141143
栄区,id141151
泉区,id141160
青葉区,id141178
都筑区,id141186</code></pre></noscript>
<p>置換programの都合上、エンコードはUTF-8です。</p>
<p><em><span style="color: #808080;">※補足</span></em><br />
<em><span style="color: #808080;">本当は置換ミスを防ぐために、被置換Wordが長い順に並べ替えた方がいいです。実際、私は南区・港南区の置換を一度ミスりました（＾＾；</span></em></p>
<p>&nbsp;</p>
<p>次に置換プログラムを実行します。</p>
<h6>replace_text.py (2.7x系)</h6>
<script src="https://gist.github.com/244a70eaee8b788fe41f.js"></script><noscript><pre><code class="language-python python">#coding:utf-8
'''
Created on 2014/03/27

@author: hitsuji
'''
import csv

# 置換リストをCSVファイルで読み込む
words_filename = 'replace_words'
document_in = 'yokohama_topo.json'
document_out = 'yokohama_topo_out.json'
words = []

def unicode_csv_reader(unicode_csv_data, dialect=csv.excel, **kwargs):
    # csv.py doesn't do Unicode; encode temporarily as UTF-8:
    csv_reader = csv.reader(utf_8_encoder(unicode_csv_data),dialect=dialect, **kwargs)
    for row in csv_reader:
        # decode UTF-8 back to Unicode, cell by cell:
        yield [unicode(cell, 'utf-8') for cell in row]

def utf_8_encoder(unicode_csv_data):
    for line in unicode_csv_data:
        yield line.encode('utf-8')

with open(words_filename + '.csv', 'rU') as csvfile:
    spamreader = unicode_csv_reader(csvfile, dialect=csv.excel)
    for row in spamreader:
        words.append(row)

text = u&quot;&quot;
with open(document_in, 'rU') as docfile:
    tmpdoc = docfile.read()
    docfile.close()
    text = tmpdoc.encode('utf-8')

for pair in words:
    text = text.replace(pair[0], pair[1])

with open(document_out, 'w') as f:
    f.write(text)
    f.close() </code></pre></noscript>
<p>前々回作成したTopoJSONファイルについて、区名=&gt;コードに置換します。</p>
<p>&nbsp;</p>
<p>長くなったので、今回はここで一旦切ります。</p>
<p>次回は、置換後のTopoJSONファイルを使って重複ラベル表示の問題を解決したいと思います。</p>
<p>それでは、また〜☆</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.hitsuji.me/replacement-from-word-name-to-its-code/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>地図に区名を表示する</title>
		<link>http://blog.hitsuji.me/show-words-name-on-yokohama-city-map/</link>
		<comments>http://blog.hitsuji.me/show-words-name-on-yokohama-city-map/#comments</comments>
		<pubDate>Thu, 29 May 2014 05:43:43 +0000</pubDate>
		<dc:creator><![CDATA[kapibarawebmaster1515]]></dc:creator>
				<category><![CDATA[可視化]]></category>
		<category><![CDATA[D3.js]]></category>
		<category><![CDATA[TopoJSON]]></category>

		<guid isPermaLink="false">http://blog.hitsuji.me/?p=57</guid>
		<description><![CDATA[前回作成した横浜市地図に、区名ラベルを入れてみたいと思います。 &#160; とりあえず、ラベルを貼るソースコードを追加してみます。L78-92が追記箇所です。 index.html &#160; 前・・・<a class="readon" href="http://blog.hitsuji.me/show-words-name-on-yokohama-city-map/">続きを読む</a>]]></description>
				<content:encoded><![CDATA[<p><a title="GeoJSONからTopoJSON形式に変換して地図を表示する" href="http://blog.hitsuji.me/make-topojson-file-and-show-map/">前回作成した</a>横浜市地図に、区名ラベルを入れてみたいと思います。</p>
<p>&nbsp;</p>
<p>とりあえず、ラベルを貼るソースコードを追加してみます。L78-92が追記箇所です。</p>
<h6>index.html</h6>
<script src="https://gist.github.com/8dcbe9ed22625d39f547.js"></script><noscript><pre><code class="language-html html">&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;ja&quot;&gt;
&lt;head&gt;
&lt;meta charset=&quot;utf-8&quot;&gt;
&lt;script src=&quot;http://d3js.org/d3.v3.min.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;http://d3js.org/topojson.v0.min.js&quot;&gt;&lt;/script&gt;
&lt;style type=&quot;text/css&quot;&gt;
h1 {
    font-size: 16px;
}
svg {
    border: 1px solid #aaaaaa;
}
.subunit-boundary {
  fill: none;
  stroke: #777;
  stroke-dasharray: 2,2;
  stroke-linejoin: round;
}
.cityname-label {
    fill-opacity: .5;
    font-size: 8px;
    font-weight: 300;     
    text-anchor: middle;
}
&lt;/style&gt;
&lt;title&gt;Yokohama city map&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h1&gt;Yokohama city map&lt;/h1&gt;
&lt;div id=&quot;map&quot;&gt;&lt;/div&gt;

&lt;script type=&quot;text/javascript&quot;&gt;
    var map_width = 500;
    var map_height = 650;
    var svg;
    
    d3.json(&quot;yokohama_topo.json&quot;, function(error, json) {
        if( !error ) {
            main(json);
        }
        return;
    });
    
    function main(topo) {
        
        var labelLineHight = 16;
         // svgを追加
        svg = d3.select(&quot;body&quot;).append(&quot;svg&quot;)
                .attr(&quot;width&quot;, map_width)
                .attr(&quot;height&quot;, map_height);
                
        // 横浜市のmapを描画する
        var yokohama = topojson.object(topo, topo.objects.yokohama);
        console.log(yokohama);
        
        // 横浜市を中心に指定したメルカトル図法で10万分の1で描画する
        var projection = d3.geo.mercator()
                .center([139.59,35.45])
                .scale(100000)
                .translate([map_width / 2, map_height / 2]);
        
        // pathを作成する
        var path = d3.geo.path().projection(projection);
        svg.append(&quot;path&quot;)
          .datum(yokohama)
          .attr(&quot;d&quot;, path);
        
        // 色を塗る
        svg.selectAll(&quot;path&quot;).attr(&quot;fill&quot;, &quot;#bee59e&quot;);
        
        // 内部境界に線を引く
        svg.append(&quot;path&quot;)
           .datum(topojson.mesh(topo, topo.objects.yokohama, function(a, b) { return a !== b; }))
           .attr(&quot;d&quot;, path)
           .attr(&quot;class&quot;, &quot;subunit-boundary&quot;);
        
        // 区名ラベル貼り
        svg.selectAll(&quot;.cityname-label&quot;)
            .data(yokohama.geometries)
          .enter()
            .append(&quot;text&quot;)
                .attr(&quot;class&quot;, function(d) {
                    return &quot;cityname-label&quot;;
                    })
                .attr(&quot;transform&quot;, function(d) {
                    return &quot;translate(&quot; + path.centroid(d) + &quot;)&quot;;
                })
                .attr(&quot;dy&quot;, &quot;.35em&quot;)
                .text(function(d) {
                    return d.properties.name;
                });
    }
&lt;/script&gt;

&lt;/body&gt;
&lt;/html&gt;</code></pre></noscript>
<p>&nbsp;</p>
<p>前回の記事でTopoJSONを作成するときに、区名をnameプロパティに設定して書き出していました。</p>
<pre class="command">topojson -p name=N03_004 -p name -o yokohama_topo.json yokohama.geojson</pre>
<p>元のGeoJSONファイルのN03_004フィールドには区名が入っていたのでした。</p>
<p>Safariでプロパティを確認してみます。</p>
<p><img class="alignnone size-large_for_2x wp-image-58" src="http://blog.hitsuji.me/app/wp-content/uploads/2014/05/debugger-1200x727.png" alt="debugger" width="600" height="363" /></p>
<p>確かに、データ要素を覗いてみると、d.properties.nameに&#8221;青葉区&#8221;と入っています。これをラベルとして素直に出力したのが今回のコードです。実行結果は次の通り。（下の画像をクリックすると、地図ページに飛びます）</p>
<p><a href="http://static.hitsuji.me/map-yokohama03/"><img class="alignnone size-medium_for_2x wp-image-60" src="http://blog.hitsuji.me/app/wp-content/uploads/2014/05/yokohama_map03-443x600.png" alt="yokohama_map03" width="221" height="300" /></a></p>
<p>出来た・・・と思ったら、区名が重複して出力されてしまいました。島など境界線が分かれている箇所は、データ上それぞれ別要素になっているので、余計なラベルまで貼られてしまいました。</p>
<p>&nbsp;</p>
<p>次回は、この問題を解決しようと思います。</p>
<p>ではではまたね</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.hitsuji.me/show-words-name-on-yokohama-city-map/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>GeoJSONからTopoJSON形式に変換して地図を表示する</title>
		<link>http://blog.hitsuji.me/make-topojson-file-and-show-map/</link>
		<comments>http://blog.hitsuji.me/make-topojson-file-and-show-map/#comments</comments>
		<pubDate>Mon, 26 May 2014 03:48:47 +0000</pubDate>
		<dc:creator><![CDATA[kapibarawebmaster1515]]></dc:creator>
				<category><![CDATA[可視化]]></category>
		<category><![CDATA[D3.js]]></category>
		<category><![CDATA[GeoJSON]]></category>
		<category><![CDATA[TopoJSON]]></category>

		<guid isPermaLink="false">http://blog.hitsuji.me/?p=35</guid>
		<description><![CDATA[前回記事で作成したGeoJSONファイルから、TopoJSONファイルを作成して、地図を表示するところまでやってみます。 &#160; TopoJSONファイルに変換する GeoJSONファイルをTo・・・<a class="readon" href="http://blog.hitsuji.me/make-topojson-file-and-show-map/">続きを読む</a>]]></description>
				<content:encoded><![CDATA[<p><a title="ShapeファイルからGeoJsonファイルを作成する" href="http://blog.hitsuji.me/make-shape-file/">前回記事</a>で作成したGeoJSONファイルから、TopoJSONファイルを作成して、地図を表示するところまでやってみます。</p>
<p>&nbsp;</p>
<h4>TopoJSONファイルに変換する</h4>
<p>GeoJSONファイルをTopoJSONファイルに変換します。GeoJSONとTopoJSONの違いは何？という方は、前回ご紹介したサイト</p>
<p>＊D3.jsとTopoJSONで地図を作る　<a title="D3.jsとTopoJSONで地図を作る" href="http://ja.d3js.node.ws/blocks/mike/map/" target="_blank">http://ja.d3js.node.ws/blocks/mike/map/</a></p>
<p>の&#8221;データの変換&#8221;の章に簡単に書いてあります。</p>
<p>&nbsp;</p>
<p>さて、ターミナルを開きます。</p>
<pre class="command">topojson -p name=N03_004 -p name -o yokohama_topo.json yokohama.geojson</pre>
<p>ここでは、&#8221;yokohama.geojson&#8221; というGeoJSONファイルを、&#8221;yokohama_topo.json&#8221;というTopoJSONファイルに変換しつつ、N03_004というフィールドをnameという名前に変更・付与しています。QGISで開くと分かりますが、N03_004フィールドに区名が入っているので、それをTopoJSONファイルに属性値として出力します。</p>
<p>&nbsp;</p>
<h4>TopoJSONファイルを読み込み、横浜市地図を表示する</h4>
<p>いよいよ地図を表示します。下の画像をクリックすると、地図のページに飛びます。</p>
<p><a href="http://static.hitsuji.me/map-yokohama02/" target="_blank"><img class="alignnone" src="http://blog.hitsuji.me/app/wp-content/uploads/2014/05/yokohama_map02-452x600.png" alt="yokohama_map02" width="226" height="300" /></a></p>
<p>&nbsp;</p>
<p>ソースコードはこんな感じです。</p>
<h6>index.html</h6>
<script src="https://gist.github.com/d693035582291061e644.js"></script><noscript><pre><code class="language-html html">&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;ja&quot;&gt;
&lt;head&gt;
&lt;meta charset=&quot;utf-8&quot;&gt;
&lt;script src=&quot;http://d3js.org/d3.v3.min.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;http://d3js.org/topojson.v0.min.js&quot;&gt;&lt;/script&gt;
&lt;style type=&quot;text/css&quot;&gt;
h1 {
    font-size: 16px;
}
svg {
    border: 1px solid #aaaaaa;
}
.subunit-boundary {
  fill: none;
  stroke: #777;
  stroke-dasharray: 2,2;
  stroke-linejoin: round;
}
&lt;/style&gt;
&lt;title&gt;Yokohama city map&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h1&gt;Yokohama city map&lt;/h1&gt;
&lt;div id=&quot;map&quot;&gt;&lt;/div&gt;

&lt;script type=&quot;text/javascript&quot;&gt;
    var map_width = 500;
    var map_height = 650;
    var svg;
    
    d3.json(&quot;yokohama_topo.json&quot;, function(error, json) {
        if( !error ) {
            main(json);
        }
        return;
    });
    
    function main(topo) {
        
        var labelLineHight = 16;
         // svgを追加
        svg = d3.select(&quot;body #map&quot;).append(&quot;svg&quot;)
                .attr(&quot;width&quot;, map_width)
                .attr(&quot;height&quot;, map_height);
                
        // 横浜市のmapを描画する
        var yokohama = topojson.object(topo, topo.objects.yokohama);
        console.log(yokohama);
        
        // 横浜市を中心に指定したメルカトル図法で10万分の1で描画する
        var projection = d3.geo.mercator()
                .center([139.59,35.45])
                .scale(100000)
                .translate([map_width / 2, map_height / 2]);
        
        // pathを作成する
        var path = d3.geo.path().projection(projection);
        svg.append(&quot;path&quot;)
          .datum(yokohama)
          .attr(&quot;d&quot;, path);
        
        // 色を塗る
        svg.selectAll(&quot;path&quot;).attr(&quot;fill&quot;, &quot;#bee59e&quot;);
        
        // 内部境界に線を引く
        svg.append(&quot;path&quot;)
           .datum(topojson.mesh(topo, topo.objects.yokohama, function(a, b) { return a !== b; }))
           .attr(&quot;d&quot;, path)
           .attr(&quot;class&quot;, &quot;subunit-boundary&quot;);
           
    }
&lt;/script&gt;

&lt;/body&gt;
&lt;/html&gt;</code></pre></noscript>
<p>&nbsp;</p>
<p>JSONファイルを読み込む関数d3.jsonは非同期処理になります。読み込み完了したら第2引数のfunction(error,json) {&#8230;} が呼び出される仕組みなので、そのCallback関数の中にjsonファイルを使った処理、すなわち地図を描く処理を書いています。</p>
<p>&nbsp;</p>
<p>d3.geo.mercator().center([139.59,35.45])&#8230; center()で、地図中心を経度と緯度で指定しています。経度と緯度はGoogle Mapで調べてから調整しました。</p>
<p>&nbsp;</p>
<p>今回は、地図を表示することろまで！</p>
<p>それではまた〜</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.hitsuji.me/make-topojson-file-and-show-map/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
