javascript - D3 - 以点击的国家为中心

标签 javascript jquery d3.js

在下面的示例中,我看到当用户选择一个国家/地区时,地球会旋转并以该国家/地区为中心。我如何对其进行编码,以便在单击某个国家/地区时,地球以该国家/地区为中心?

D3 Globe

我曾尝试在鼠标悬停事件之前添加一个点击处理程序,但它似乎不起作用。有什么想法吗?

.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/

相关文章:

javascript - 在 Javascript 中使用外部变量

javascript - 在 IF 函数中使用 OR 运算符时,比较条件的顺序是否重要?

javascript - 克隆到新的动态生成的下拉列表后,删除先前选择中的选定项目

javascript - 如何在 y 轴上展开路径?

javascript - 在没有翻译的情况下使用 d3 SVG Scale

javascript - 保持 D3 圆形包的纵横比 - 响应式设计

javascript - 仅在 Ctrl + 滚动时缩放

javascript - Uncaught Error :cannot call methods prior to initialization;

php - 在选择选项标签中循环 Ajax 响应

jquery - 将 $(this) 传递给函数