我正在尝试使用d3js创建一个地图,并使用特定属性标记点要素.Below是我尝试的代码,标签似乎不起作用。
尝试添加标签时,我可能做错了什么。谢谢。
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.land {
stroke: #ff0f00;
fill: none;
}
.state-boundary {
fill: none;
stroke: #000fff;
}
.labels {
fill: #444;
font-family:arial;
font-size:0.7em;
}
text {
font: 12px sans-serif;
text-anchor: middle;
}
</style>
<body>
<script src="d3.v3.min.js" type="text/JavaScript"></script>
<script src="https://d3js.org/topojson.v2.min.js"></script>
<script>
var width = 1000,
height = 900;
var projection = d3.geo.albers()
.scale(1000)
.translate([width / 2, height / 2]);
var path = d3.geo.path().projection(projection);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
d3.json("http://bl.ocks.org/mbostock/raw/4090846/us.json", function(error, us) {
if (error) throw error;
svg.insert("path", ".graticule")
.datum(topojson.feature(us, us.objects.land))
.attr("class", "land")
.attr("d", path);
svg.insert("path", ".graticule")
.datum(topojson.mesh(us, us.objects.states, function(a, b) {
return a !== b;
}))
.attr("class", "state-boundary")
.attr("d", path);
});
d3.csv("nfl_teams.csv", function(error, data) {
svg.selectAll("circle")
.data(data)
.enter()
.append("circle")
.attr("cx", function(d) {
return projection([d.Longitude, d.Latitude])[0];
})
.attr("cy", function(d) {
return projection([d.Longitude, d.Latitude])[1];
})
.attr("r", 15)
.style("fill", "none")
.style("stroke", "red");
svg.selectAll(".labels")
.data(data)
.enter().append("text")
.attr("class", "labels")
.text(function(d) { return d.properties.Team; })
.attr("x", function(d) {
return projection([d.Longitude, d.Latitude])[0];
})
.attr("y", function(d) {
return projection([d.Longitude, d.Latitude])[1];
})
});
d3.select(self.frameElement).style("height", height + "px");
</script>
&#13;
nfl_teams.csv
Team,Latitude,Longitude
Chicago,41.53,-87.38
Green Bay,44.3,-88.01
Arizona,33.27,-112.05
Atlanta,33.45,-84.23
Baltimore,39.17,-76.37
Buffalo,42.54,-78.53
Carolina,35.14,-80.5
Cincinnati,39.06,-84.31
Cleveland,41.3,-81.41
Dallas,32.47,-96.48
Denver,39.43,-105.01
Detroit,42.2,-83.03
Houston,29.46,-95.22
Indianapolis,39.46,-86.09
Jacksonville,30.2,-81.4
Kansas City,39.06,-94.37
Miami,25.46,-80.12
Minnesota,44.59,-93.13
New England,42.21,-71.04
New Orleans,29.58,-90.07
New York Giants,40.43,-74.01
New York Jets,40.43,-74.01
Oakland,37.47,-122.13
Philadelphia,39.57,-75.07
Pittsburgh,40.26,-80
LA Rams,38.38,-90.11
San Diego,32.43,-118.09
San Francisco,37.48,-122.24
Seattle,47.36,-122.2
Tampa,27.57,-82.27
Tennessee,36.09,-86.48
Washington,38.54,-77.01
答案 0 :(得分:1)
由于这是您的CSV:
Team,Latitude,Longitude
Chicago,41.53,-87.38
Green Bay,44.3,-88.01
这将是d3.csv
函数加载数据后的数据数组:
[{
Team: "Chicago",
Latitude: "41.53",
Longitude: "-87.38"
}, {
Team: "Green Bay",
Latitude: "44.3",
Longitude: "-88.01"
},{
...
}]
如您所见,您的数据对象中没有任何名为properties
的密钥。因此,修复很简单。而不是:
.text(function(d) { return d.properties.Team; })
应该是:
.text(function(d) { return d.Team; })