Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
363 views
in Technique[技术] by (71.8m points)

javascript - Add names of the states to a map in d3.js

I am using albersUSA projection to display a map. I want to add the name of the states to each state.

This is what I tried, and i can see the names of the states in the source, but I don't see them rendered. What am i doing wrong?

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];
    });

  });
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

OK for anyone wondering, this is how I managed to do it:

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


  });
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...