How should I write the attr fill function in D3, in order to color the map according to the rate of urbanization inside the map JSON API?
e.g: this is the api for Afghanistan
{"type":"Topology","transform":{"scale":[0.03600360036003601,0.017366249624962495],"translate":[-180,-90]},"objects":{"countries":{"type":"GeometryCollection","geometries":[{"type":"Polygon","arcs":[[0,1,2,3,4,5]],"id":"Afghanistan" ,"rate":3.96}
if I write:
svg.selectAll('path.land')
.data( topojson.feature(
worldJson, worldJson.objects.countries).features )
.enter().append ('path')
.attr ('class', 'land')
.attr ('d', path)
.attr ("fill", (d,i)=>{
const countries = d.id;
if(countries == "Afghanistan")
{
return "blue";
}
else {return "grey";}})
Afghanistan will turn blue, however if I write:
svg.selectAll('path.land')
.data( topojson.feature(
worldJson, worldJson.objects.countries).features )
.enter().append ('path')
.attr ('class', 'land')
.attr ('d', path)
.attr ("fill", (d,i)=>{
const urban = d.rate;
if(urban == 3.96)
{
return "blue";
}
else {return "grey";}})
Afghanistan will not turn blue. How should I fix this?
Topojson ignores the rate
attribute.
To add custom data, you have to use the properties
attribute like in the following example:
var worldJson = {"type":"Topology","transform":{"scale":[0.03600360036003601,0.017366249624962495],"translate":[-180,-90]},"objects":{"countries":{"type":"GeometryCollection","geometries":[{"type":"Polygon","arcs":[[0]],"id":"Afghanistan" ,"properties":{"rate":3.96}}]}},"arcs":[[[7080,6666],[-5,5],[-10,-13]]]}
Then you can use it this way: const urban = d.properties.rate;
.
You can try it on this Runkit https://runkit.com/dmnized/5b695446f8311b00125e4494.