javascript – 地图名称未在d3地图中显示

我正在尝试使用以下代码添加要在地图中显示的区域名称:

<!DOCTYPE html>
<meta charset="utf-8">
<style>

svg {
  border: 1px solid #ccc;
}

path {
  fill: #ccc;
  stroke: #fff;
  stroke-width: .5px;
}

path:hover {
  fill: #00AEEC;
}

.place,
.place-label {
  fill: #444;
}

text {
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-size: 10px;
  pointer-events: none;
}

</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://d3js.org/topojson.v1.min.js"></script>
<script>

var width = 960,
    height = 500;

var path = d3.geo.path();

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);


d3.json("tunisia.json", function(error, topology) {

  console.clear();

  var featureCollection = topojson.feature(topology, topology.objects.governorates);
  var bounds = d3.geo.bounds(featureCollection);

  var centerX = d3.sum(bounds, function(d) {return d[0];}) / 2,
      centerY = d3.sum(bounds, function(d) {return d[1];}) / 2;

  var projection = d3.geo.mercator()
    .scale(3000)
    .center([centerX, centerY]);

  path.projection(projection);

  svg.selectAll("path")
      .data(featureCollection.features)
      .enter().append("path")
      .attr("d", path); 

    svg.selectAll(".place-label")
      .data(featureCollection.features)
    .enter().append("text")
      .attr("class", "place-label")
      .attr("transform", function(d) { console.log(d.geometry.coordinates);return "translate(" + projection(d.geometry.coordinates[0]) + ")"; })
      .attr("x", function(d) { return d.geometry.coordinates[0] > -1 ? 6 : -6; })
      .attr("dy", ".35em")
      .style("text-anchor", function(d) { return d.geometry.coordinates[0] > -1 ? "start" : "end"; })
      .text(function(d) { console.log(d.properties.gov_name_f);return d.properties.gov_name_f; });


});

</script>
</body>
</html>

但这似乎不起作用.你能看出出了什么问题吗?

这是关于要点的代码:https://gist.github.com/mohamed-ali/856f17a3450fc93ffbc2

最佳答案 您可以这样做以将标签放置在路径的质心中:

svg.selectAll(".place-label")
  .data( featureCollection.features)
.enter().append("text")
  .attr("class", "place-label")
  .attr("transform", function(d) { return "translate(" + path.centroid(d) + ")"; }) //get the centroid of the path to put labels.
  .attr("dy", ".35em")
  .text(function(d) { return d.properties.gov_name_f; });

工作代码here

希望这可以帮助!

点赞