TopoJSON << properties >>字段,如何用d3.js获取值?

KoG*_*Gor 3 d3.js topojson

我有TopoJSON文件,它看起来像这样:

{"type":"Topology","transform":{"scale":[0.03600360003702599,0.0040674580654071245],"translate":[-179.9999967702229,41.18684289776669],"objects":{"country":{"type":"GeometryCollection","geometries":[{"type":"Polygon","arcs":[[0]],"properties":{"AREA":29809500,"PERIMETER":21822.4,"region":"XYZ"}},…

我想在我的d3.js代码中使用属性值("AREA","PERIMETER","region").我试图获得一些值,但它不起作用:

d3.json("map_topo.json", function(error, map) {
svg.append("path")
.datum(topojson.object(map, map.objects.country).geometries)
.attr("d", path)
.style("fill", function(d) {
if (d.properties.region == "XYZ")
 {return "red"}
else {return "gray"}
})  
Run Code Online (Sandbox Code Playgroud)

我做错了什么?

UPD:问题是在@ChrisWilson的帮助下解决的,问题在于追加一条路径,而不是选择所有路径.工作代码(对于topojson.v0.js):

d3.json("map_topo.json", function(error, map) {
svg.selectAll("path")
.data(topojson.object(map, map.objects.country).geometries)
.enter().append("path")
.attr("d", path)
.style("fill", function(d) {
if (d.properties.region == "XYZ")
{return "red"}
else {return "gray"}
}); 
Run Code Online (Sandbox Code Playgroud)

对于topojson.v1.js使用topojson.feature方法(请看下面的评论).

Chr*_*son 5

您似乎制作了一张大型地图,而不是一系列path代表国家/ 地区的对象.试试这个:

d3.json("map_topo.json", function(error, map) {
    svg.selectAll("path")
       .data(topojson.feature(us, us.objects.counties).features)
       .enter()
       .append("path")
       .attr("d", path)
       .style("fill", function(d) {
           if (d.properties.region == "XYZ")
               {return "red"}
           else {return "gray"}
       });
Run Code Online (Sandbox Code Playgroud)

我不能确定这会在没有看到TopoJSON文件的情况下工作,但基本上你需要一个topojson能产生数组的方法.

请参阅等值区域示例以获得一个好的示例:状态被映射为一个路径,.mesh()而县被映射为单个对象,如上面的代码.