Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

d3.js

topojson

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).

like image 992
KoGor Avatar asked Jan 17 '26 05:01

KoGor


1 Answers

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.

like image 111
Chris Wilson Avatar answered Jan 19 '26 19:01

Chris Wilson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!