TopoJSON ‹‹properties›› field, how to get values with d3.js?

夙愿已清 提交于 2019-12-06 08:11:10

问题


I have TopoJSON file, it looks like this:

{"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"}},…

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

What I'm doing wrong?

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

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


回答1:


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

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.

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.



来源:https://stackoverflow.com/questions/16305419/topojson-properties-field-how-to-get-values-with-d3-js

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!