d3.js - 为什么我不能使用 topojson 获得 d3.js 地图来渲染?
问题描述
我在让 d3 从 topoJson 数据中渲染 geoAlbersUsa 投影时遇到了一些困难。我正在显示一个空白屏幕,但没有返回任何错误。geoJson 数据似乎很好,但由于某种原因它没有呈现路径。任何帮助将不胜感激!
以下是相关代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script src="https://d3js.org/d3.v6.min.js"></script>
<script src="https://unpkg.com/topojson-client@3"></script>
</head>
<body>
<script>
const width = 1000;
const height = 600;
const projection = d3.geoAlbersUsa()
.translate([width / 2, height / 2])
.scale(800);
const path = d3.geoPath(projection);
const svg = d3.select("body")
.append("svg")
.attr("height", height)
.attr("width", width)
.style("display", "block")
.style("margin", "auto");
d3.json("https://d3js.org/us-10m.v1.json").then(data => {
svg.selectAll(".states")
.data(topojson.feature(data, data.objects.states).features)
.attr("d", path)
.style("fill", "none")
.attr("class", "states")
.style("stroke", "black")
.style("stroke-width", "2px")
});
</script>
</body>
</html>
解决方案
您需要加入一个元素:
.data(topojson.feature(data, data.objects.states).features)
.join("path") // here
.attr("d", path)
.style("fill", "none")
.attr("class", "states")
.style("stroke", "black")
.style("stroke-width", "2px")
推荐阅读
- c# - Unity Post-processing PostProcessEffectRenderer 显示在编辑器中但不在构建中
- sql - 在 Redshift 查询中为 max(date) 函数指定意外事件
- java - 如何使用正则表达式拆分此字符串“-25+26+78-21”以获得-25、26、78、-21?
- python - 如何在python中将两个pdf页面拼接成一个
- git - 如何在 GitHub 上使用其他人的 pull request 中的代码?
- python - 如何将以 1 开头的数字添加到列表中?
- ruby-on-rails - GoDaddy VPS 配置上的 Ruby on Rails
- selenium - 当我有匹配的胶水代码时,eclipse 会引发以下错误 - 步骤“用户已经在登录页面”没有匹配的胶水代码
- arrays - kotlin“包含”没有按预期工作
- javascript - NotFoundError:在 removeChild() 上找不到节点