将颜色填充到 d3 世界地图(等值线图)

filling color into d3 world map (choropleth map)

D3中的attr填充函数应该怎么写,才能根据地图内部的城市化率给地图上色JSONAPI?

例如:这是阿富汗api

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

如果我写:

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

阿富汗不会变蓝。我应该如何解决这个问题?

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