2013-02-23 37 views
5

我製作了一個d3符號地圖,並希望用戶能夠通過名爲'type'的屬性過濾點。有三種類型:a,b,c,每種都有一個關聯的html複選框,選中時應顯示a類型的點,未選中時應刪除這些點。我想知道將check/uncheck事件傳入d3的最佳方法是什麼?我想如果有一種方法將選中的類型傳遞給select.filter(),那將是最好的方法。下面是代碼:帶複選框過濾功能的d3地圖

HTML

<div class="filter_options"> 
<input class="filter_button" id="a_button" type="checkbox">a</input><br> 
<input class="filter_button" id="b_button" type="checkbox">b</input><br> 
<input class="filter_button" id="c_button" type="checkbox">c</input><br> 
</div> 

JS

queue() 
.defer(d3.json, "basemap.json") 
.defer(d3.json, "points.json") 
.await(ready); 

function ready(error, base, points) { 

var button = 

svg.append("path") 
    .attr("class", "polys") 
    .datum(topojson.object(us, base.objects.polys)) 
    .attr("d", path); 

svg.selectAll(".symbol") 
    .data(points.features) 
.enter().append("path") 
    .filter(function(d) { return d.properties.type != null ? this : null; }) 
    .attr("class", "symbol") 
    .attr("d", path.pointRadius(function(d) { return radius(d.properties.frequency * 50000); })) 
    .style("fill", function(d) { return color(d.properties.type); });; 

目前,該過濾器設置爲捕獲所有點:

.filter(function(d) { return d.properties.type != null ? this : null; }) 

我想用戶會能夠改變這一點。

乾杯

回答

5

像這樣的東西應該工作。爲您的複選框添加一個值屬性,以便您知道它們指的是什麼。

d3.selectAll(".filter_button").on("change", function() { 
    var type = this.value, 
    // I *think* "inline" is the default. 
    display = this.checked ? "inline" : "none"; 

    svg.selectAll(".symbol") 
    .filter(function(d) { return d.properties.type === type; }) 
    .attr("display", display); 
}); 
+0

令人驚歎。謝謝。當檢查框時,它就像一個魅力一樣,但取消選中不會消除這些點。任何想法,爲什麼會這樣? – rysloan 2013-02-23 20:16:34

+0

拯救生命。謝謝。 – rysloan 2013-02-23 20:40:05

+0

當然可以。那麼你有沒有檢查工作? – 2013-02-23 20:40:52