我应该如何在D3中编写 attr 填充函数,以便根据地图JSON API中的城市化速度为地图着色?
例如:这是阿富汗的api
{“类型”:“拓扑”,“转换”:{“比例”:[0.03600360036003601,0.017366249624962495],“翻译”:[-180,-90]},“对象”:{“国家”:{ “ type”:“ GeometryCollection”,“ geometries”:[{“ type”:“ Polygon”,“ arcs”:[[0,1,2,3,4,5]],“ id”:“阿富汗” ,“ rate”:3.96}
如果我写:
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";}})
阿富汗会变成蓝色,但是如果我这样写:
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";}})
阿富汗不会变成蓝色。我该如何解决?
答案 0 :(得分:1)
Topojson忽略rate
属性。
要添加自定义数据,您必须像以下示例一样使用properties
属性:
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]]]}
然后您可以通过以下方式使用它:const urban = d.properties.rate;
。
您可以在此Runkit https://runkit.com/dmnized/5b695446f8311b00125e4494上进行尝试。