2014-06-24 36 views

回答

2

創建這種方法在這裏的粗例如:http://jsfiddle.net/djmartin_umich/9VJHe/

1)首先我達到包含所有狀態的質心JSON文件:https://bitbucket.org/john2x/d3test/src/2ce4dd511244/d3/examples/data/us-state-centroids.json。爲了這個例子的目的,我將json複製到jsfiddle。

var labels = {"type":"FeatureCollection","features":[ 
        {"type":"Feature","id":"01","geometry":{"type":"Point","coordinates":[-86.766233,33.001471]},"properties":{"name":"Alabama","population":4447100}}, 
        {"type":"Feature","id":"02","geometry":{"type":"Point","coordinates":[-148.716968,61.288254]},"properties":{"name":"Alaska","population":626932}}, 

2)然後,我添加一個SVG元素的圖表,將包含所有標籤:

 var labelG = d3.select("svg") 
      .append("svg:g") 
      .attr("id", "labelG") 
      .attr("class", "Title"); 

3)接着我添加了一個SVG文本元素在標籤JSON每個狀態:

labelG.selectAll("text") 
     .data(labels.features) 
     .enter().append("svg:text") 

4)然後我使用質心座標定位文本元素。要做到這一點,您應該使用圖表中的投影將座標轉換爲相對的x和y值。

  .attr("x", function(d){return project(d.geometry.coordinates)[0];}) 
     .attr("y", function(d){return project(d.geometry.coordinates)[1];}) 
     .attr("dx", "-1em"); 

下面是最終的結果: enter image description here

你會注意到兩個問題:

  • 沒有足夠的空間來顯示在東北部各州的所有名稱
  • 標籤不居中非常好

這兩個問題都可以通過手動移動座標來更改標籤json來解決。

請注意,我用這個問題作爲我的答案的基礎:https://groups.google.com/forum/#!topic/d3-js/uAWkwnuNQ3Q

+0

在https://gist.github.com/proclamo/0fc304040b7036eb7785這個新的示例使用狀態的質心/國家將標籤貼:https://gist.github.com/proclamo/0fc304040b7036eb7785。看起來很有希望。 –

+0

謝謝你的分享。該方法工作:) –

相關問題