我對 d3js 很陌生,并試圖了解使用資料和資料將資料附加到元素之間的區別。我已經在網上閱讀了相當多的材料,我認為我從理論上理解了發生了什么,但我仍然缺乏直觀的理解。具體來說,我有一個使用 topojson 創建地圖的情況。我正在使用 d3js v7。
在第一個實體中,我使用以下代碼在 div 中創建地圖(假設高度、寬度、投影等設定正確):
var svg = d3.select("div#map").append("svg")
.attr("width", width)
.attr("height", height)
.attr("transform", "translate(" 15 "," 0 ")");
var path = d3.geoPath()
.projection(projection);
var mapGroup = svg.append("g");
d3.json("json/world-110m.json").then(function(world){
console.log(topojson.feature(world, world.objects.land))
mapGroup.append("path")
.datum(topojson.feature(world, world.objects.land))
.attr("class", "land")
.attr("d", path);
});
topojson 功能的控制臺日志如下所示:

地圖出來的很好(在 css 檔案中指定了樣式):
但是如果我將資料更改為資料,地圖就會消失。我正在努力提高我對這是如何作業的理解,并且在閱讀了我可以在網上找到的內容后,我有點掙扎。有人可以解釋在這種情況下使用的資料和資料之間的區別,以及為什么一個有效而另一個無效?
謝謝你的幫助!
uj5u.com熱心網友回復:
data()和之間有幾個區別datum(),但對于您問題的范圍,主要區別在于data()僅接受 3 件事:
- 陣列;
- 一個功能;
- 什么都沒有(在那種情況下,它是一個吸氣劑);
如您所見,topojson.feature(world, world.objects.land)是一個物件。因此,您需要在data()這里使用的所有內容(同樣,不是慣用的 D3,我只是在解決您的具體問題)就是用陣列包裝它:
.data([topojson.feature(world, world.objects.land)])
這是您使用的代碼data():
顯示代碼片段
var svg = d3.select("div#map").append("svg")
.attr("width", 500)
.attr("height", 300)
.attr("transform", "translate(" 15 "," 0 ")");
var path = d3.geoPath();
var mapGroup = svg.append("g");
d3.json("https://raw.githubusercontent.com/d3/d3.github.com/master/world-110m.v1.json").then(function(world) {
const projection = d3.geoEqualEarth()
.fitExtent([
[0, 0],
[500, 300]
], topojson.feature(world, world.objects.land));
path.projection(projection);
mapGroup.append("path")
.data([topojson.feature(world, world.objects.land)])
.attr("class", "land")
.attr("d", path);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<script src="https://unpkg.com/topojson@3"></script>
<div id="map"></div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/326015.html
標籤:javascript json d3.js 拓扑文件
上一篇:d3-將配色方案轉換為粉彩
