在下面的示例中,我看到当用户选择一个国家/地区时,地球会旋转并以该国家/地区为中心。我如何对其进行编码,以便在单击某个国家/地区时,地球以该国家/地区为中心?
我曾尝试在鼠标悬停事件之前添加一个点击处理程序,但它似乎不起作用。有什么想法吗?
.on("click", function(d) {
var rotate = projection.rotate(),
focusedCountry = country(countries, this),
p = d3.geo.centroid(focusedCountry);
svg.selectAll(".focused").classed("focused", focused = false);
//Globe rotating
(function transition() {
d3.transition()
.duration(2500)
.tween("rotate", function() {
var r = d3.interpolate(projection.rotate(), [-p[0], -p[1]]);
return function(t) {
projection.rotate(r(t));
svg.selectAll("path").attr("d", path)
.classed("focused", function(d, i) { return d.id == focusedCountry.id ? focused = d : false; });
};
})
})();
})
最佳答案
首先像这样创建一个点击路径:
.on("click", function(d){rotateMe(d);})
更改点击数据的代码。获取点击路径的id,并获取其国家数据。
var rotateMe = function(d) {
var rotate = projection.rotate(),
focusedCountry = country(countries, d.id),//get the clicked country's details
p = d3.geo.centroid(focusedCountry);
console.log(focusedCountry, "hello")
svg.selectAll(".focused").classed("focused", focused = false);
//Globe rotating
(function transition() {
d3.transition()
.duration(2500)
.tween("rotate", function() {
var r = d3.interpolate(projection.rotate(), [-p[0], -p[1]]);
return function(t) {
projection.rotate(r(t));
svg.selectAll("path").attr("d", path)
.classed("focused", function(d, i) { return d.id == focusedCountry.id ? focused = d : false; });
};
})
})();
};
工作代码here
关于javascript - D3 - 以点击的国家为中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36526617/