gpt4 book ai didi

javascript - D3 : How to load features from a JSON string in D3

转载 作者:行者123 更新时间:2023-11-30 20:57:13 24 4
gpt4 key购买 nike

我遇到过很多使用 JSON.parse(string) 方法从 JSON 字符串创建 JSON 对象的示例,但是我不清楚在使用 JSON.parse 时如何加载该对象的特性。例如,从下面的链接(json 文件:canada.topo.json)复制并粘贴文本,我有以下代码:

<!DOCTYPE html>
<meta charset="utf-8">
<style>
path {
stroke: white;
stroke-width: 0.25px;
fill: grey;
}
</style>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script>
<script src="https://d3js.org/topojson.v1.min.js"></script>
<script>
var json = "jsonfile"
jobj = JSON.parse(json)
var width = 960,
height = 1160;

var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
//what to do next is my problem
//A simple way to just project a map typically is with the following, which fails in this case:
function(error, us) {
svg.append("path")
.data(jobj)
//How do I load the features from the jobj object??
.feature(us, us.objects.Canada).features
.attr("d", d3.geo.path().projection(d3.geo.mercator()));
}
//As a side point, this does not throw any errors, but nothing happens of course as there are no features
var svg = d3.select("body")
d3.select('.countries').selectAll('path')
.data(jobj)
svg.append("path")
.attr("d", d3.geo.path().projection(d3.geo.mercator()));
</script>

问题:如何将 jobj 的特性加载到 D3 中?

https://github.com/returnOfTheYeti/CanadaJSON/blob/master/canada.topo.json

最佳答案

https://github.com/returnOfTheYeti/CanadaJSON/blob/master/canada.topo.json此链接是指向 github 页面的链接,而不是指向您的 json 文件本身。

你应该使用这个 url - https://raw.githubusercontent.com/returnOfTheYeti/CanadaJSON/master/canada.topo.json您可以通过单击“原始”按钮获取任何文件的此 url。

enter image description here

所以使用 d3.json 方法你可以这样加载这个文件:

d3.json('https://raw.githubusercontent.com/returnOfTheYeti/CanadaJSON/master/canada.topo.json', function(data) {
console.log(data); // <= object with loaded data
console.log(topojson.feature(data, data.objects.Canada).features); // <= features
});

检查 this jsFiddle .

更新:

如果您将 json 字符串存储在某个变量中,您可以通过这种方式获取特征并创建 map :

var json = `...json string...`;

var jobj = JSON.parse(json); // parse string

var width = 960,
height = 1160;

var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);

// get features array with topojson.feature method, bind it with .data method and create map
svg.selectAll("path")
.data(topojson.feature(jobj, jobj.objects.Canada).features)
.enter()
.append("path")
.attr("d", d3.geo.path().projection(d3.geo.mercator()));

示例 your data .

关于javascript - D3 : How to load features from a JSON string in D3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47525763/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com