我正在尝试结合bl.ocks(Choropleth和click-to-zoom)上的d3示例中的两个示例。现在我有了这个(响应是来自我后端的AJAX响应,传递了像显示等值时所需的us.json这样的东西)。
风格
.background {
fill: transparent;
pointer-events: all;
}
#states {
fill: #aaa;
}
#state-borders {
fill: none;
stroke: #fff;
stroke-linejoin: round;
pointer-events: none;
}
的Javascript
response = parseJSON(response);
var us = response['us'];
var data = response['data'];
var reportID = response['reportID'];
var thresholds = response['thresholds'];
var colorScheme = response['colorScheme'];
var max = response['max'];
var options = response['options'];
var name = options['name'];
var width = 900, height = 500, centered;
//define the display threshold
var color = d3.scale.threshold()
.domain(thresholds)
// .range(["#f2f0f7", "#dadaeb", "#bcbddc", "#9e9ac8", "#756bb1", "#54278f"]); //purple
.range(colorScheme); //all colors
var rateById = {};
for(var i in data){
rateById[data[i]['id']] = +data[i]['value'];
}
var projection = d3.geo.albersUsa()
.scale(1070)
.translate([width / 2, height / 2]);
var path = d3.geo.path()
.projection(projection);
var svg = d3.select("#" + rowID + " .choropleth:nth-of-type(" + (parseInt(options['i']) + 1) + ")").append("svg")
.attr("width", width)
.attr("height", height)
var g = svg.append("g");
svg.append("g")
.attr("class", "counties")
.selectAll("path")
.data(topojson.feature(us, us.objects.counties).features)
.enter().append("path")
.attr("d", path)
.style("fill", function(d) { return color(rateById[d.id]); });
g.append("g")
.attr("id", "states")
.selectAll("path")
.data(topojson.feature(us, us.objects.states).features)
.enter().append("path")
.attr("d", path)
g.append("path")
.datum(topojson.mesh(us, us.objects.states, function(a, b) { return a !== b; }))
.attr("id", "state-borders")
.attr("d", path);
svg.append("rect")
.attr("class", "background")
.attr("width", width)
.attr("height", height)
.on("click", clicked);
function clicked(d){
console.log(typeof d);
var x, y, k;
if(d && centered !== d){
var centroid = path.centroid(d);
x = centroid[0];
y = centroid[1];
k = 4;
centered = d;
}else{
x = width / 2;
y = height / 2;
k = 1;
centered = null;
}
console.log(x + "\n" + y + "\n" + k + "\n" + centered);
g.transition()
.duration(750)
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")scale(" + k + ")translate(" + -x + "," + -y + ")")
.style("stroke-width", 1.5 / k + "px");
}
我把console.log(typeof d);
检查参数的状态是否传递给click函数并发现它是null
但是如果我取出添加了县行的块然后点击函数传递适当的值,缩放功能按预期工作。我尝试重新排列以SVG元素顺序添加的各种块,但没有任何成功。我找不到任何关于传递给click函数的参数究竟来自哪里的文档,所以我不知道是什么原因导致它为null。
答案 0 :(得分:0)
我通过移动创建县的块来解决问题
svg.append("g")
.attr("class", "counties")
.selectAll("path")
.data(topojson.feature(us, us.objects.counties).features)
.enter().append("path")
.attr("d", path)
.style("fill", function(d) { return color(rateById[d.id]); })
.on("click", clicked);
到最后(在我定义clicked
函数之前)并将click事件处理程序放在该元素而不是rect上。