我正在尝试从 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.json
d3 v5 中的函数只是一个解析实用程序,fetch
如文档所解释的那样构建在 of 之上。
fetch() 方法接受一个强制参数,即您要获取的资源的路径。它返回一个 Promise,该 Promise 解析为对该请求的响应,无论它是否成功。您还可以选择传入一个 init 选项对象作为第二个参数(请参阅请求)。
重要的部分是它返回 a 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。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句