【发布时间】:2018-11-08 16:35:17
【问题描述】:
给一个外部 json 文件“us-states.json”这个结构:
{
"type": "FeatureCollection",
"features": [
{ "type": "Feature", "properties": { "GEO_ID": "0400000US23", "STATE": "23", "NAME": "Maine", "LSAD": "", "CENSUSAREA": 30842.923000 }, "geometry": { "type": "MultiPolygon", "coordinates": [ [ [ [ -67.619761, 44.519754 ], [ -67.615410, 44.521973 ], [ -67.587738, 44.516196 ] ... ] ] ] } } ...
我能够渲染地图并使用 data.csv 中的值对其进行着色,但无法附加地图标签并让它们出现(底部脚本的最后)。
<script type="text/javascript">
var width = 800;
var height = 460;
var projection = d3.geo.albersUsa()
.translate([width/2, height/2])
.scale([1000]);
var path = d3.geo.path()
.projection(projection);
var color = d3.scale.linear()
.range(["rgb(255,90,95)","rgb(84,36,55)","rgb(0,80,160)"]);
var svg = d3.select("body")
.append("svg")
.attr("class","map")
.attr("width", width)
.attr("height", height)
.attr("align","center");
d3.csv("data.csv", function(data) {
color.domain([1,2,3]);
d3.json("us-states.json", function(json) {
for (var i = 0; i < data.length; i++) {
var dataState = data[i].state;
var dataValue = data[i].value;
var dataLink = data[i].link;
for (var j = 0; j < json.features.length; j++) {
var jsonState = json.features[j].properties.NAME;
var jsonStateCoords = json.features[j].geometry.coordinates
if (dataState == jsonState) {
json.features[j].properties.value = dataValue;
json.features[j].properties.link = dataLink;
json.features[j].properties.coordinates = jsonStateCoords;
break;
}
}
};
svg.selectAll("path")
.data(json.features)
.enter()
.append("path")
.attr("d", path)
.style("stroke", "#fff")
.style("stroke-width", "1")
.style("fill", function(d) {
var value = d.properties.value;
if (value) {
return color(value);
} else {
return "rgb(213,222,217)";
}
})
// part of the script that isn't working
svg.selectAll("text")
.data(json.features)
.enter()
.append("svg:text")
.attr("d", path)
.text(function(d){return d.properties.state; })
.attr("x", function(d){ return d.properties.coordinates[0] })
.attr("y", function(d){ return d.properties.coordinates[1] })
.attr("text-anchor","middle")
.attr('font-size', '13px')
.attr('color', 'white');
});
</script>
我可以console.log(jsonStateCoords) 看到他们。为什么我无法访问返回d.properties.coords.x 或d.properties.coords.y 的字段值?取而代之的是d.properties.coords is undefined。谢谢
【问题讨论】:
-
是的,结果相同
-
你能创建一个功能小提琴或 sn-p 吗?所以我们可以帮助你
-
您是否要在地图上添加州标签文本?
-
是的,这是我要添加到 svg 中的最后一个 .append()
标签: javascript json d3.js