来自2个不同数据源(d3.js)的d.properties的内部html

时间:2018-09-21 21:21:17

标签: javascript html d3.js

我有两个并排的d3弦图,它们都来自同一个geojson,但是代表了不同年份,当前和2014年的不同数据。

我加载了两个不同年份的数据:

var currentMap = d3.map();
var map2014 = d3.map();

d3.queue()

.defer(d3.csv, "data/overdoses_2018_updated.csv", function(d) { 
    if (isNaN(d.DrugOverdoseMortalityRate)) {
        console.log('nan')
    } else {
        currentMap.set(d.FIPS, +d.DrugOverdoseMortalityRate); 
    }

})
.defer(d3.csv, "data/overdoses_2014_updated.csv", function(e) { 
    if (isNaN(e.DrugOverdoseMortalityRate)) {
        console.log('nan')
    } else {
        map2014.set(e.FIPS, +e.DrugOverdoseMortalityRate); 
    }

})
  .await(ready);

并成功渲染了当年的地图-

    //GeoPath
  var geoPath = d3.geoPath()
    .projection( albersProjection );



    d3.select("svg.current").selectAll("path")
    .data( CaliforniaCountiesOverdoses.features )
    .enter()
    .append( "path" )
    .attr( "d", geoPath )
        .attr("class","counties")
        .attr("fill", function(d) { 
            var value = currentMap.get(d.properties.ID);
            return (value != 0 ? current_color(value) : "grey");  
})
    // setting popup based on current data
    .on("mouseover", function(d) {         
            countyDiv .html('<br/>' + d.properties.NAME + '<br/>' + d.properties.DrugOverdo + ' overdoses per 10,000')  
            })

现在,我对2014年也是如此:

 d3.select("svg.map2014").selectAll("path")
    .data( CaliforniaCountiesOverdoses.features )
    .enter()
    .append( "path" )
    .attr( "d", geoPath )
        .attr("class","counties-2014")

        .attr("fill", function(e) { 
            var value2014 = map2014.get(e.properties.ID);
            return (value2014 != 0 ? current_color(value2014) : "grey");  
})
     // trying to set popup based on 2014 data
    .on("mouseover", function(e) {        
            county2014Div .html('<br/>' + e.properties.NAME + '<br/>' + e.properties.DrugOverdo + ' overdoses per 10,000')  

一切正常-县填充色反映了2014年数据,但是输入到county2014Div中的html不是2014年数据,它仍然是当前数据。如何从2014数据源(而不是当前数据)读取d.properties?提前致谢。

1 个答案:

答案 0 :(得分:1)

您正在使用CaliforniaCountiesOverdoses.features中的数据。

就像您在fill()中进行操作一样,它基于path的ID查找值。

d3.select("svg.map2014").selectAll("path")
    .data( CaliforniaCountiesOverdoses.features )
    .enter()
    .append( "path" )
    .attr( "d", geoPath )
    .attr("class","counties-2014")
    .attr("fill", function(e) { 
        var value2014 = map2014.get(e.properties.ID);
        return (value2014 != 0 ? current_color(value2014) : "grey");  
    })
    .on("mouseover", function(e) {        
        var value2014 = map2014.get(e.properties.ID);
        county2014Div .html('<br/>' + e.properties.NAME + '<br/>' + value2014 + ' overdoses per 10,000');

通过删除所有重复的代码,可以大大简化您的代码。