为什么 Svg 路径出现在控制台而不是屏幕上?

Why does Svg path appears in console but not on screen?

我想知道是否有人可以帮助我。

我正在尝试根据我已转换的以下 topoJSON 渲染新加坡地图。

下面是我的代码:

<style>
    path {
        /*fill: #ccc;*/
        stroke: rgba(12, 12, 12, 0.96);
        stroke-linejoin: round;
    }
</style>
    <svg width="900" height="600"></svg>

<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/topojson.v2.min.js"></script>
<script>
     var svg = d3.select("svg"),
         width = +svg.attr("width"),
         height = +svg.attr("height");

//     var projection = d3.geoAlbers();
     var projection = d3.geoMercator()
         .center([0, 5 ])
         .scale(900)
         .rotate([-180,0]);

     var path = d3.geoPath(projection);

    d3.queue()
        .defer(d3.json, "data/sgtopo.json")
        .await(ready);

    function ready(error, sg){
        if(error) throw error;
        var topofeature = topojson.feature(sg, sg.objects["sg-"]);
        svg.append("g")
         .selectAll("path")
         .data(topofeature.features)
         .enter()
         .append("path")
         .attr("d", path);


    }
</script>
</html>

虽然我在控制台上看到生成的路径:页面仍然空白。 非常感谢任何帮助,谢谢!

您需要将 stroke 添加到路径中,因为默认情况下它是白色的。

svg.append("g")
     .selectAll("path")
     .data(topofeature.features)
     .enter()
     .append("path")
     .attr("d", path)
     .attr("stroke", "black"); <-- Add this

正如其他答案的评论中所述,绘图发生在屏幕之外。这是对 d3.js 地图进行故障排除的常见问题:未抛出任何错误,但未绘制任何数据。在这种情况下,问题通常是您选择了不正确的投影参数。

如果我用你的 topojson 代替一个世界 json 这是我的结果:

它以 180 度 east/west 和北五度为中心。这集中在印度尼西亚以东的太平洋地区。然而,新加坡位于东约 104 度和北约 1 度。所以你的投影参数应该更像:

     var projection = d3.geoMercator()
     .center([103.833333, 1.283333 ])
     .scale(900)

事实上,您的比例可以更大,以便进一步放大。使用 900 的比例和上面指定的中心,我得到这样的结果:

使用

     var projection = d3.geoMercator()
     .center([103.833333, 1.283333 ])
     .scale(60000)

和你的数据(以及上面的代码),我得到了类似的东西:

此外,对于墨卡托投影,您不需要使用旋转,因为无论您将地图居中放置在何处,地图都会正确对齐(与圆锥投影不同)。只需将其以特征中心的坐标为中心就足够了。