0

tl;博士

我可以使用如下数据创建元素吗:

[{"id": 1, ...}, {"id: 2, ...}, ..]

并使用如下所示的数据更新元素的属性:

[2, 4, 7]

(其中数组的元素是初始数据集的 id 的子集)。

长版

我的数据如下所示:

[
{
    "id": 1, 
    "latitude": 38.314552, 
    "longitude": -88.9025347755102, 
    "name": "JEFFERSON COUNTY JAIL ", 
    "official_name": "Jefferson County Justice Center", 
    "url": "https://www.ice.gov/detention-facilities/facilities/jeffeil.htm"
}, 
{
    "id": 2, 
    "latitude": 41.875702, 
    "longitude": -87.63072, 
    "name": "CHICAGO HOLD ROOM ", 
    "official_name": "Chicago Hold Room", 
    "url": ""
}, 
{
    "id": 3, 
    "latitude": 43.407029, 
    "longitude": -88.704349, 
    "name": "DODGE COUNTY JAIL, JUNEAU ", 
    "official_name": "Dodge Detention Facility", 
    "url": "https://www.ice.gov/detention-facilities/facilities/dodgewi.htm"
}, 
...
]

我把它放在这样的 SVG 地图上:

var projection = d3.geo.albersUsa()
    .scale(scale)
    .translate([width / 2, height / 2]);

var facilityCircles = svg.append("svg:g")
    .attr("id", "facilities");

d3.json("data/facilities.json", function(facilities) {
  var positions = [];
  var positionsByFacilityId = {};
  var pointSize = 5;
  facilities.forEach(function(facility) {
    var loc = [facility.longitude, facility.latitude];
    var pos = projection(loc);
    positions.push(pos);
    positionsByFacilityId[facility.id] = pos; 
  });
  facilityCircles.selectAll("circle")
                 .data(facilities, function(d) { return d.id; })
                 .enter().append("svg:circle")
                 .attr("data-facility-id", function(d, i) { return d.id; })
                 .attr("cx", function(d, i) { return positionsByFacilityId[d.id][0]; })
                 .attr("cy", function(d, i) { return positionsByFacilityId[d.id][1]; })
                 .attr("r", function(d, i) { return pointSize; });
 }

但是,稍后,我想根据另一个数据对象更新圆圈的属性,这只是一个 id 数组,表示初始数据中 id 属性的子集,例如[2, 4, 5]

我可以做这样的事情来更新仅映射到具有给定 id 的数据对象的选定元素的属性吗?

      facilitiesSubset = [2, 4, 5];
      facilityCircles.selectAll("circle")
                 .data(facilitiesSubset)
                 .attr("fill", "green");

或者,我应该只从初始数据中提取 id 并使用那些data()用于创建元素的调用吗?

4

1 回答 1

1

为了使这更容易一点,我建议稍微更改命名约定:

var facilityCircleContainer = svg.append("svg:g")
    .attr("id", "facilities");

由于 svg:g 对象实际上不是圆圈,它只是持有它们。那么:

  var facilityCircles = facilityCircleContainer.selectAll("circle")
                 .data(facilities, function(d) { return d.id; })
                 .enter().append("svg:circle")
                 .attr("data-facility-id", function(d, i) { return d.id; })
                 .ect(...)

facilityCircles 现在指的是带有附加数据的圆圈。根据数组更新填充非常简单:

facilityCircles.attr("fill", function(d){
   facilitiesSubset.indexOf(d.id) != -1 ? "green" : "red"});
于 2013-06-03T16:14:53.237 回答