【问题标题】:D3 - Center the globe to the clicked countryD3 - 以点击的国家为中心
【发布时间】:2016-04-10 06:29:58
【问题描述】:

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

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; });
            };
            })
     })();
})

【问题讨论】:

    标签: javascript jquery d3.js


    【解决方案1】:

    首先创建一个点击路径如下:

     .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

    【讨论】:

    • 你知道什么好玩吗?如果你越过国际日期变更线,地球会转回来!例如:将地球旋转两到三圈,然后将给定的国家定位在靠近中心的位置。如果你点击那个国家,你会期望地球会旋转一点点并以国家为中心,对吗?但是,相反,它会转回那两三圈,然后以国家为中心!
    • 不!无法重新创建:) 尝试了很多次,但没有发现任何异常...
    • 真的吗?也许只是我的浏览器?试试这个:您的投影以西非为中心开始。将投影向西移动(使地球以正常方式旋转,从西向东),直到您将澳大利亚置于投影的正中心。现在点击澳大利亚。在我的浏览器中,地球向东旋转了一圈,然后以澳大利亚为中心。
    • 没有在 FF 版本 28 操作系统上尝试过:linux ubuntu 和 chrome(ver:47.0.2526.80) 无法重新创建..完全按照您的指示进行..奇怪。
    • 非常,确实!我使用的是 Windows 7 64,它发生在 Chrome 49 和 FF 45 中!
    猜你喜欢
    • 2021-06-24
    • 1970-01-01
    • 2015-04-06
    • 1970-01-01
    • 2016-07-31
    • 1970-01-01
    • 2012-02-14
    • 1970-01-01
    • 2013-06-28
    相关资源
    最近更新 更多