D3:从json数据中选择路径时遇到问题
D3: Having trouble selecting a path from json data
尽管阅读了其他人发布的许多关于此事的问题和答案,但我在从外部json
坐标文件为路径分配id时遇到了困难。文件中的数据看起来是这样的(它也在我的html的标题中被引用,见下文):
var neighborhoods_json = {
"type": "FeatureCollection",
"features": [
{ "type": "Feature", "properties": { "Name": "Roslindale", "density": 5.5800 }, "geometry": { "type": "MultiPolygon", "coordinates": [ [ [ [ -71.1259, 42.2720 ], [ -71.1257, 42.2723 ], [ -71.1256, 42.2724 ], [ -71.1255, 42.2725 ],....
我见过其他人问同样的问题,答案是添加这一行来创建每条路径的id:
.attr("id", function(d) {return d.id;})
但是我的json
数据不包含id
,所以我想我应该使用Name
:
.attr("id", function(d) {return d.Name;})
然后,我尝试选择创建的路径之一,使用Name
作为id
。我们的想法是简单地选择其中一个路径,然后将其填充颜色更改为红色。但我要么没有正确分配id,要么没有正确选择路径。有人能告诉我我做错了什么吗?
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://maptimeboston.github.io/d3-maptime/example3/neighborhoods.js"></script>
</head>
<body>
<script>
var width = 700,
height = 580;
var svg = d3.select( "body" )
.append( "svg" )
.attr( "width", width )
.attr( "height", height );
var neighborhoods = svg.append( "g" );
var albersProjection = d3.geo.albers()
.scale( 190000 )
.rotate( [71.057,0] )
.center( [0, 42.313] )
.translate( [width/2,height/2] );
var geoPath = d3.geo.path()
.projection( albersProjection );
neighborhoods.selectAll( "path" )
.data( neighborhoods_json.features )
.enter()
.append("path")
.attr( "d", geoPath)
.attr("id", function(d) {return d.Name;})
.attr("fill", "steelblue");
neighborhoods.select("path#Roslindale")
.attr("fill", "red");
</script>
在id
函数中,Name
属性嵌套在properties
属性中
neighborhoods.selectAll( "path" )
.data( neighborhoods_json.features )
.enter()
.append("path")
.attr( "d", geoPath)
.attr("id", function(d) {return d.properties.Name;})
.attr("fill", "steelblue");
工作jsfiddle
相关文章:
- 将PHP变量传递给jQuery时遇到问题
- 我的jQuery插件参数没有正确启动,遇到了问题
- Javascript:使用绝对路径设置img src
- 如何在d3.js中返回路径的y坐标
- 复制图像路径以单击它
- 从模块内部访问Express装载路径
- JS文件的路径正在消失
- 使用onclick绘制SVG路径
- jpm的默认Firefox路径没有'不起作用
- 如何使用jquery将base64图像路径转换为真实路径
- 可以用'吗/'在相对路径中
- Canvas+svg路径动画,在路径中的特定点暂停一段时间,然后继续
- 在AJAX回调和呈现PIXIJS之间处理程序流时遇到了问题
- 将jQuery转换为用户脚本的普通Javascript时遇到问题
- 将Windows文件路径组织到文件夹中
- Ajax URL路径未替换当前URL
- 如何使用Javascript上传给定路径的文件
- 如何将要单独填充的每个HTML画布路径/形状分开
- 在使用angular.js路由路径时遇到问题
- D3:从json数据中选择路径时遇到问题