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

时间:2017-01-23 06:42:56

标签: javascript d3.js geojson topojson

我想知道是否有人可以伸出援助之手。

我试图通过我转换的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>

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

enter image description here

enter image description here

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

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

如果我用topojson代替世界json,这是我的结果:

enter image description here

它的中心位于东西180度和北纬五度。它位于印度尼西亚东部的太平洋地区。然而,新加坡位于东经104度,北纬约1度。所以你的投影参数应该更像是:

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

事实上,为了进一步放大,您的比例可能会大得多。以900的比例和上面指定的中心,我得到这样的东西:

enter image description here

使用

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

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

enter image description here

此外,使用墨卡托投影时,您无需使用旋转,因为无论您将地图放在哪里,地图都会正确对齐(与锥形投影不同)。只需将其置于功能中心的坐标上即可。

相关问题