9

マップを表示するために albersUSA 投影法を使用しています。各州に州の名前を追加したい。

これは私が試したもので、ソースで州の名前を見ることができますが、それらがレンダリングされているのはわかりません。私は何を間違っていますか?

var width = 1060,
height = 600,

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);

svg.append("rect")
    .attr("class", "background")
    .attr("width", width)
    .attr("height", height)
    .on("click", click)
    .on("mousemove", mousemove);

var g = svg.append("g")
    .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")")
    .append("g")
    .attr("id", "states");

var projection = d3.geo.albersUsa()
    .scale(width)
    .translate([0, 100]);

var path = d3.geo.path()
    .projection(projection);

draw();

function draw(){

  d3.json("readme.json", function(json) {
    g.selectAll("path")
    .data(json.features)
    .enter()
    .append("path")
    .attr("d", path)
    .append("svg:text")
    .text(function(d){
        return d.properties.name;
    })
    .attr("x", function(d){
        return -path.centroid(d)[0];
    })
    .attr("y", function(d){
        return  -path.centroid(d)[1];
    });

  });
}
4

2 に答える 2

27

疑問に思っている人なら誰でもOK、これが私がなんとかした方法です:

function draw(){

  d3.json("readme.json", function(json) {
    g.selectAll("path")
    .data(json.features)
    .enter()
    .append("path")
    .attr("d", path)
    .on("click", click);

    g.selectAll("text")
    .data(json.features)
    .enter()
    .append("svg:text")
    .text(function(d){
        return d.properties.name;
    })
    .attr("x", function(d){
        return path.centroid(d)[0];
    })
    .attr("y", function(d){
        return  path.centroid(d)[1];
    })
    .attr("text-anchor","middle")
    .attr('font-size','6pt');


  });
}
于 2012-12-16T06:45:18.243 に答える
7

あなたが自分で提供した答えに同様のアプローチを取りましたが、「セントロイド」がすべての州名をどこに置くかが気に入りませんでした。たとえば、ハワイ、ルイジアナ、ミシガン、フロリダなどです。そこで、これらの状態の dx と dy の状態情報の json データにプロパティを追加し、描画関数にコードを追加しました。

変更された状態の例を次に示します (小さくするために座標を削除しています)。

    {
        "geometry": { "type": "Polygon", "coordinates": [] },
        "type": "Feature",
        "id": "12",
        "properties": { "name": "Florida", "abbr": "FL", "dx": "1em" }
    },
    {
        "geometry": { "type": "MultiPolygon", "coordinates": [] },
        "type": "Feature",
        "id": "15",
        "properties": { "name": "Hawaii", "abbr": "HI", "dx": "1.15em", "dy": "1.25em" }
    },

ラベルを描画する関数の部分は次のとおりです。

        g.selectAll("text")
            .data(json.features)
            .enter()
            .append("text")
            .attr("transform", function (d) { return "translate(" + path.centroid(d) + ")"; })
            .attr("dx", function (d) { return d.properties.dx || "0"; })
            .attr("dy", function (d) { return d.properties.dy || "0.35em"; })
            .text(function (d) { return d.properties.abbr; });
于 2014-04-02T18:23:01.480 に答える