2016-11-30 6 views
3

D3.jsを使用して、Mercator投影法を使用してUSAの地理的地図を描画しています。この地図は、米国の各都市の人口を表しています。人口データは、次のファイルに格納されます都市の場所を示す
D3.jsを使用して地理的地図の都市にラベルを付ける方法は?

https://gist.githubusercontent.com/d3byex/65a128a9a499f7f0b37d/raw/176771c2f08dbd3431009ae27bef9b2f2fb56e36/us-cities.csv

円はマップに表示されます。

コードが下に貼り付けられます:

<!DOCTYPE html> 
<html> 
<head> 
    <meta name="description" content="D3byEX 12.18" /> 
    <meta charset="utf-8"> 
</head> 
<body> 
    <script src="http://d3js.org/d3.v3.min.js"></script> 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/queue-async/1.0.7/queue.min.js"></script> 
    <script> 

     var width = 1000, height = 500; 
     var svg = d3.select('body') 
      .append('svg') 
      .attr({ 
       width: width, 
       height: height 
      }); 

     var usDataUrl = 'https://gist.githubusercontent.com/d3byex/65a128a9a499f7f0b37d/raw/176771c2f08dbd3431009ae27bef9b2f2fb56e36/us-states.json', 
      citiesDataUrl = 'https://gist.githubusercontent.com/d3byex/65a128a9a499f7f0b37d/raw/176771c2f08dbd3431009ae27bef9b2f2fb56e36/us-cities.csv'; 

     queue() 
      .defer(d3.json, usDataUrl) 
      .defer(d3.csv, citiesDataUrl) 
      .await(function (error, states, cities) { 
       var path = d3.geo.path(); 
       var projection = d3.geo.albersUsa() 
        .translate([width/2, height/2]) 
        .scale([1000]); 
       path.projection(projection); 

       svg.selectAll('path') 
        .data(states.features) 
        .enter() 
        .append('path') 
        .attr('d', path) 
        .style({ 
         fill: 'none', 
         stroke: 'black' 
        }); 

       svg.selectAll('circle') 
          .data(cities) 
          .enter() 
          .append('circle') 
          .each(function (d) { 
           var location = projection([d.longitude, d.latitude]); 
           d3.select(this).attr({ 
            cx: location[0], cy: location[1], 
            r: Math.sqrt(+d.population * 0.00004) 
           }); 
          }) 
          .style({ 
           fill: 'blue', 
           opacity: 0.75 
          }); 
      }); 
    </script> 
</body> 
</html> 



しかし、それらの上にマウスを移動しながら、それらの円に都市名のラベルを追加する方法?

答えて

3

ツールチップを作成するための最も基本的な(そして醜い)メソッドは<title>を使用している:それは今働いている

svg.selectAll('circle') 
    .data(cities) 
    .enter() 
    .append('circle') 
    .each(function (d) { 
      var location = projection([d.longitude, d.latitude]); 
      d3.select(this).attr({ 
      cx: location[0], cy: location[1], 
      r: Math.sqrt(+d.population * 0.00004) 
      }); 
    }) 
    .style({ 
      fill: 'blue', 
      opacity: 0.75 
    }) 
    .append("title") 
    .text(d=>d.name); 
+0

。 – User456898

+0

.append( "title")の前に、セミコロンを削除する必要があります。 – User456898

+0

@Laurelありがとうございます。注意を払わずにコードをコピーして貼り付けたからです。タイトルは基本的なものだと言わなければならない!より良い選択肢があります、私の答えをここで確認してください:http://stackoverflow.com/a/35665974/5768908 –

関連する問題