d3.js topoJson 图中未显示路径
-
22-12-2019 - |
题
我正在尝试使用 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
你能检查一下我做错了什么吗
解决方案
你的json文件没有问题。
您遇到的问题是您没有为您的项目定义投影 d3.geo.path()
这意味着它会回退到默认值。根据上面链接的文档:
#d3.geo.path()
使用默认设置创建一个新的地理路径生成器:这 阿尔伯斯美国 投影和点半径为 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 比例的选择是任意的,在这种情况下似乎效果很好,将其调整为适合您的任何值。
最后,您需要设置 .projection()
你的 path
在实际创建 svg 路径之前,您所做的投影。
path.projection(projection);
svg.selectAll("path")
.data(featureCollection.features)
.enter().append("path")
.attr("d", path);
这里 是一个使用您的数据的工作示例。
不隶属于 StackOverflow