javascript - D3 Geojson 地图不会显示
问题描述
我正在尝试从 Geojson 文件显示 DMA 的地图,但地图不会加载。我相信这是一个缩放/定位问题,但我发现的修复都没有奏效。寻求任何帮助。
var width = 960
var height = 500
var canvas = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height)
d3.json("nielsenDMA.json", function(error, data) {
if(error) throw error;
var projection = d3.geoMercator().fitSize([width, height], geojson);
var path = d3.geoPath().projection(projection);
g.selectAll("path")
.data(data.features)
.enter()
.append("path")
.style("fill", "red")
.style("stroke-width", "1")
.style("stroke", "black");
});
解决方案
如果没有您使用的 json 文件示例或 d3 版本,很难理解地图渲染失败的原因,因此我将假设以下内容,我认为您可能想要使用与此类似的文件一个并且您使用的是最新的 d3 版本。正如文档解释的那样,d3 v5 中的d3.json
函数只是一个基于 of 的解析实用程序。fetch
fetch() 方法接受一个强制参数,即要获取的资源的路径。它返回一个 Promise,该 Promise 解析为对该请求的响应,无论它是否成功。您还可以选择传入一个初始化选项对象作为第二个参数(请参阅请求)。
重要的部分是它返回一个Promise
,现在让我们看看文档d3.json
d3.json(input[, init])
获取指定输入 URL 处的 JSON 文件。如果指定了 init,则将其传递给底层的 fetch 调用。
第二个可选参数是一个 init 对象,它允许您使用 fetch 请求控制许多不同的设置。
那么为什么您提供的代码不起作用?好吧,您提供的回调根本没有被调用。它作为函数的第二个参数被传递,它根本不会做任何事情。
获取数据的正确方法是使用Promise
函数返回的值:
d3.json("url-to-retrieve")
.then(data => {
console.log(data);
})
.catch(err => {
console.log(err);
});
考虑到这一点,我们只需要对数据使用正确的投影,并注意您使用的是 topojson 还是 geojson 文件。
在这种情况下,此 geojson 文件适用于geoMercator
投影。
d3.json("url-to-retrieve")
.then(data => {
var width = 960,
height = 500;
// Create a projection fitted to our width/height
var projection = d3.geoMercator()
.fitSize([width, height], data);
// Creates a new geographic path generator
var path = d3.geoPath()
.projection(projection);
var svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height)
svg.append("rect")
.attr("class", "background")
.attr("fill", "#cacaca")
.attr("width", width)
.attr("height", height);
svg.append("g")
.attr("id", "dmas")
.selectAll("path")
.data(data.features)
.enter()
.append("path")
.attr('fill', 'white')
.attr('stroke', '#222')
.attr('stroke-width', '2')
.attr("d", path);
})
.catch(err => {
console.log(err);
});
这是上面代码的jsfiddle。
推荐阅读
- python - Python:打印函数没有给出异常输出
- rx-java - RxJava 从 flatmap 的下游 observable 发出初始值
- r - 如何将嵌套df中的变量中出现少于k次的所有值设置为0
- android - Webview 上没有可用的预览
- android - 检查 wifi 打印机是否忙&在 android 4.2 上打印队列
- amazon-web-services - AWS EMR 本地磁盘加密失败
- jenkins - 带有 github webhook 的詹金斯不能按预期工作
- javascript - 无法在 Firefox 中以编程方式下载 html5 下载(适用于 Safari、IE、Opera、Chrome)
- node.js - NodeJS API 开发框架
- android - 浮动操作按钮不显示图像