将状态名称添加到d3.js中的地图中

ash*_*rya 7 javascript jquery svg d3.js

我正在使用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];
    });

  });
}
Run Code Online (Sandbox Code Playgroud)

ash*_*rya 22

好的,对于任何想知道的人来说,这就是我设法做到的方式:

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');


  });
}
Run Code Online (Sandbox Code Playgroud)


jfr*_*484 7

我对你自己提供的答案采取了类似的方法,但我不喜欢"质心"放置所有州名的地方.例如,夏威夷,路易斯安那,密歇根和佛罗里达.所以我为json数据添加了属性,为这些状态添加了dx和dy的状态信息,并向绘图函数添加了代码.

以下是一些修改状态的示例(删除坐标以使其更小):

    {
        "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" }
    },
Run Code Online (Sandbox Code Playgroud)

以下是绘制标签的函数部分:

        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; });
Run Code Online (Sandbox Code Playgroud)

  • 在这里你去:https://github.com/jfren484/Sandbox/tree/master/D3Mapping (2认同)