2016-04-10 21 views
1

在下面的示例中,我看到當用戶選擇一個國家時,地球旋轉並居中該國家。我該如何編碼,以便在點擊一個國家時,地球中心位於該國?D3 - 將地球居中到所點擊的國家

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

回答

3

首先創建一個點擊這樣的路徑:

.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

+0

你知道什麼好笑的?如果您通過國際日期線,地球儀將旋轉回來!例如:旋轉地球兩三次,並將一個給定的國家放在靠近中心的地方。如果你點擊那個國家,你會期望地球旋轉一點點,然後居中國家,對吧?但是,它會旋轉這兩三次,然後將國家中心! –

+0

nopes!無法重新創建:)嘗試了很多次,但沒有發現任何不尋常的東西...... – Cyril

+0

真的嗎?也許只是我的瀏覽器?試試這個:你的投影從中部非洲西部開始。將投影向西移動(使地球從西向東旋轉,直到你在投影的中心得到澳大利亞)。現在點擊澳大利亞。在我的瀏覽器中,地球完全轉向東方,然後以澳大利亞爲中心。 –

相關問題