在d3.js中将状态的名称添加到地图 [英] Add names of the states to a map in d3.js

查看:125
本文介绍了在d3.js中将状态的名称添加到地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用albersUSA投影来显示地图。
我想为每个状态添加状态的名称。

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

  });
}


推荐答案

是我设法做到的:

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


  });
}

这篇关于在d3.js中将状态的名称添加到地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆