路径未在d3.js topoJson图中显示

时间:2014-07-31 15:24:17

标签: javascript svg d3.js topojson

我正在尝试使用topoJson绘制地图,所以我按照这个例子

但我没有得到任何东西。

这是我写的

<!DOCTYPE html>

<head>
  <meta charset="utf-8">
<style>

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

path:hover {
  fill: red;
}

</style>
</head>
<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.log(topology);

  svg.selectAll("path")
      .data(topojson.feature(topology, topology.objects.governorates).features)
      .enter().append("path")
      .attr("d", path);
});

</script>

</body>
</html>

经过一些调试后发现我的案例中的路径添加如下:

<svg width="960" height="500">
<path></path>
<path></path>
</svg>

虽然通常应该是这样的:

<svg width="960" height="500">
 <path d="M183.85631949544694,17.16574961388676L184.64695256075555,18.261986556132797L184.24437929962187,21.436416964644536L184.9109502450185,22.72190753660925L183.42733139583214,23.600229178621248L181.43637647772152,23.38526266060535L162.4858998398068,18.04698631290296L162.95134674943927,16.322885588815097L161.24381018256219,15.20848145955324L160.04585728433227,11.701769628478132L161.0879861841512,10.793553936506555L172.9773901748378,14.256236175137701Z"></path>
</svg>

这是我正在使用的数据: https://raw.githubusercontent.com/mtimet/tnacmaps/master/topojson/tunisia.json

请你检查一下我做错了什么

1 个答案:

答案 0 :(得分:8)

您的json文件没有问题。

您遇到的问题是您没有为d3.geo.path()定义投影,这意味着它会回退到默认值。根据上面链接的文件:

  

#d3.geo.path()

     

使用默认设置创建新的地理路径生成器:albersUsa投影和4.5像素的点半径。

您的地理数据是针对突尼斯地图的,因此albersUsa投影不会包含数据集中的任何坐标。这就是输出中路径数据为空的原因。

要解决此问题,您需要定义投影。您可以在加载数据时执行此操作,并且可以使用d3.geo.bounds(),传递featureCollection以查找数据的地理边界。

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

然后,从这些边界,您可以计算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]);

3000的比例选择是任意的,它在这种情况下似乎运作良好,将它调整为适合你的任何东西。

最后,在实际创建svg路径之前,您需要将.projection()的{​​{1}}设置为您所做的投影。

path

HERE是一个使用您的数据的工作示例。

相关问题