我正在尝试使用 d3 从 svg 内的 geojson 文件中绘制数据。但我得到一张空白图像。开发者工具显示 geojson 文件已加载,但 svg 元素为空
var svg = d3.select("#mainSvg");
var projection = d3.geoMercator();
var path = d3.geoPath().projection(projection);
d3.json("static/geojson/roads.geojson").then(function(geojson) {
svg.selectAll("path")
.data(geojson.features)
.enter()
.append("path")
.attr("d", path)
.style("fill", "steelblue");
}).catch(err => {
console.error(err)
});
注意:SO
https://stackoverflow.com/a/56365785/6162420
中提到的解决方案有助于解决这个问题
我不是 D3 专家,但我尝试了一些更改并且成功了。请验证渲染的地图是否准确
看起来 svg 正在渲染路径,但不适合它 对您的代码做了一些更改。
projection.fitSize([800,600],geojson);
添加它以适合路径
var svg = d3.select("#mainSvg");
// Define projection and path
var projection = d3.geoMercator();
var path = d3.geoPath().projection(projection);
// Load GeoJSON data
d3.json("https://raw.githubusercontent.com/openlayers/openlayers/main/examples/data/geojson/roads-seoul.geojson")
.then(function(geojson) {
projection.fitSize([800,600],geojson);
// Render roads
svg.selectAll("path")
.data(geojson.features)
.enter()
.append("path")
.attr("d", path)
.style("fill", "red");
})
.catch(function(err) {
console.error("Error loading or processing GeoJSON data:", err);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="src/style.css">
<script src="https://d3js.org/d3.v6.min.js"></script>
</head>
<body>
<svg id="mainSvg" width="800" height="600"></svg>
<script src="src/script.js"></script>
</body>
</html>