本文介绍了TopoJSON << properties >>字段,如何使用d3.js获取值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have TopoJSON file, it looks like this:

{type:Topology,transform:{ :[0.03600360003702599,0.00406745806540​​71245],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)。我试图获得一些值,但它不工作:

I want to use values of properties ("AREA","PERIMETER","region") in my d3.js code. I made attempt to get some values, but it didn't work:

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"}
})  

我错了?

UPD :问题已在@ChrisWilson的帮助下解决,问题在于添加一个

UPD: issue was solved with help of @ChrisWilson, problem was in appending one path, instead of selecting ALL paths. Working code (for 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"}
}); 

对于topojson.v1.js,使用 topojson.feature 方法

For topojson.v1.js use topojson.feature method (look comments below).

推荐答案

您似乎正在制作一张大型地图,而不是一系列路径代表国家的对象。尝试这样:

You appear to be making one large map, not a series of path objects representing countries. Try this:

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

我不能确定这将工作没有看到TopoJSON文件,但基本上你需要一个 topojson 方法,将产生一个数组。

I can't be sure this will work without seeing the TopoJSON file, but basically you need a topojson method that will produce an array.

有关示例,请参见:状态映射为一个路径与 .mesh(),同时县被映射为单独的对象像上面的代码。

See the choropleth map example for a good example: The states are mapped as one path with .mesh() while the counties are mapped as individual objects like the code above.

这篇关于TopoJSON << properties >>字段,如何使用d3.js获取值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 21:04