1

私はd3.jsの初心者です。私は topoJSON データを使用してマップをレンダリングしていますが、これまでのところうまく機能しています。各国・地域の上にテキストや円などのデータを重ねたいのですが、壁にぶつかっています。次のようなコードがあります。

var countries = g.append("g")
    .attr("id", "countries")
    .selectAll("path")
    .data(topojson.feature(collection, collection.objects.countries).features)
    .enter().append("path")
    .attr("d", path)
    .style("fill", colorize)
    .attr("class", "country")
    .on("click", clicked)

これにより、マップが適切にレンダリングされます。その上にいくつかの円を重ねるために、次のことを行います。

countries
    .append("circle")
    .attr("r", function(d, i, j) {
      return 10; // for now
    })
    // getCentroid below is a function that returns the 
    // center of the poligon/path bounding box
    .attr("cy", function(d, i, j) { return getCentroid(countries[0][j])[0]})
    .attr("cx", function(d, i, j) { return getCentroid(countries[0][j])[1]})
    .style("fill", "red")

これはかなり面倒ですが (特に、countries 配列にアクセスする方法)、国を表すパスごとに円を追加することに成功しています。問題は、円が SVG マークアップに存在するのに、ドキュメントにまったく表示されないことです。私は明らかに何か間違ったことをしていますが、それが何であるかがわかりません。

4

1 に答える 1

2

circle問題は、要素を要素に追加していることですpath。これは SVG では実行できません。gそれらを親要素に追加する必要があります。コードは次のようになります。

var countries = g.selectAll("g.countries")
  .data(topojson.feature(collection, collection.objects.countries).features)
  .enter().append("g")
  .attr("id", "countries");

countries.append("path")
  .datum(function(d) { return d; })
  .attr("d", path)
  // etc

countries.append("circles")
  // etc
于 2013-12-13T11:28:35.687 に答える