来自外部数据的 D3 路径未出现

D3 Paths from external data not appearing

我已经从 OSM 下载了一个文件并使用了一些坐标来练习从 GeoJSON 加载数据并将它们写入 SVG。大多数 JS 代码取自 D3Vienno 的地图教程,但即使我没有收到错误,我也无法在屏幕上显示任何内容。这是 JS 文件:

window.onload = function(){

var canvas = d3.selectAll("body").append("svg")
    .attr("width", 600)
    .attr("height", 600)

d3.json("test.geojson", function (data){

    var group = canvas.selectAll("g")
    .data(data)
    .enter()
    .append("g")

    var projection= d3.geo.albers();

    var path = d3.geo.path().projection(projection); //.scale(450).translate([0, 1980]);

    var areas = group.append("path")
        .attr("d", path)
        .attr("class", "area")
        .style("stroke-width", 1)
        .style("fill", "none")
        .style("stroke", "steelblue");


});
}

GeoJSON 文件已通过 jsonformatter 验证,我还构建了一个 JSFiddle 以查看是否有所不同。

如果我不注释掉 .scale(450).translate([0, 1980]) 部分,我会得到一个 "is not a function error",但它在 API 中,我相信它的格式正确。

这里还有 HTML:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script type="text/javascript" src="http://localhost:8080/d3.min.js"></script>
    <!--<script src="test.geojson"></script>-->
    <script type="text/javascript" src="mapPractice.js"></script>
</head>
<body>

</body>
</html>

如果我不注释掉 GeoJSON 的脚本标签,我会得到 "unexpected token error : in the GeoJSON file and this continues to happen until I delete everything but the coordinates, and then I get "Cannot read 属性 'length' of null" in the D3 file。抱歉这样的多-部分问题,但几天来我一直在努力理解这个问题,但我只是在兜圈子。

d3.json() 可能有点难以理解。埋在the explanation,你会看到:

the callback is invoked with two arguments: the error, if any, and the parsed JSON

所以,你可以试试

d3.json("test.geojson", function (error, data) {

回调的第一个参数是错误(如果您的 json 文件被正确读取,它将为 null 或未定义)。

.scale().translate()都是d3.geo.projection, not of d3.geo.path()的方法。你可能想要这样的东西:

var projection= d3.geo.albers()
  .scale(450).translate([0, 1980]);   // Call .scale() and .translate() on the projection!

var path = d3.geo.path().projection(projection);

此外,在您的 JSFiddle 中,您将像这样绑定数据:

var group = canvas.selectAll("g")
  .data(data.coordinates)

因为这只会绑定坐标数组,所以没有输入到需要 GeoJSON 的地理路径生成器。要呈现 LineString,您需要这样绑定:

var group = canvas.selectAll("g")
  .data([data])

检查您可以看到的 SVG 源代码,这确实插入了路径,尽管它不会被渲染,因为它太小并且不在屏幕上。 This 应该给你一个很好的起点,从哪里优化缩放和平移以按照你需要的方式呈现它。