D3.js D3 v5中的投影不使用坐标数据
我正试图用D3V5制作一张世界各地陨石着陆的地图。我有地图显示。正在加载陨石json文件中的坐标(lat,long)。我试图在D3.js D3 v5中的投影不使用坐标数据,d3.js,D3.js,我正试图用D3V5制作一张世界各地陨石着陆的地图。我有地图显示。正在加载陨石json文件中的坐标(lat,long)。我试图在.attr中使用它们来表示“cx”和“cy”。当我console.log在.attr中显示坐标时,它们会显示出来,但是当我试图将它们通过投影以便它们在地图上正确显示时,我得到以下错误:未捕获(承诺中)类型错误:无法读取null的属性“坐标” 有人能帮我弄清楚怎么让它工作吗?感谢你能提供的任何帮助 此处是指向代码笔的链接: 我的代码是: const w = 960; con
.attr
中使用它们来表示“cx”和“cy”。当我console.log
在.attr
中显示坐标时,它们会显示出来,但是当我试图将它们通过投影以便它们在地图上正确显示时,我得到以下错误:未捕获(承诺中)类型错误:无法读取null的属性“坐标”
有人能帮我弄清楚怎么让它工作吗?感谢你能提供的任何帮助
此处是指向代码笔的链接:
我的代码是:
const w = 960;
const h = 600;
const svg = d3.select(".map")
.append("svg")
.attr("height", h)
.attr("width", w);
let projection = d3.geoMercator()
.translate([w/2, h/2])
.scale(140);
const path = d3.geoPath()
.projection(projection);
let tooltip = d3.select("body")
.append("div")
.attr("class", "tooltip");
const files = ["https://unpkg.com/world-atlas@1.1.4/world/110m.json", "https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/meteorite-strike-data.json"];
Promise.all(files.map((url) => d3.json(url))).then(function(data) {
svg.append("g")
.attr("class", "country")
.selectAll("path")
.data(topojson.feature(data[0], data[0].objects.countries).features)
.enter().append("path")
.attr("d", path);
svg.selectAll(".meteor")
.data(data[1].features)
.enter().append("circle")
.attr("class", "meteor")
.attr("cx", (d) => {
console.log(d.geometry.coordinates[0]);
let coords = projection([d.geometry.coordinates[0], d.geometry.coordinates[1]]);
return coords[0];
})
.attr("cy", (d) => {
let coords = projection([d.geometry.coordinates[0], d.geometry.coordinates[1]]);
return coords[1];
})
.attr("r", 6);
});
您的数据缺少某些位置的坐标,例如:
{
"type": "Feature",
"geometry": null,
"properties": {
"mass": "2250",
"name": "Bulls Run",
"reclong": null,
"geolocation_address": null,
"geolocation_zip": null,
"year": "1964-01-01T00:00:00.000",
"geolocation_state": null,
"fall": "Fell",
"id": "5163",
"recclass": "Iron?",
"reclat": null,
"geolocation_city": null,
"nametype": "Valid"
}
},
这将生成您看到的错误,停止附加圆
您可以尝试使用以下方法将其过滤掉:
svg.selectAll(".meteor")
.data(data[1].features.filter(function(d) {
return d.geometry; // return only features with a geometry
}) )
给我们:
更新笔:
另外,我将很快注意到:
projection([d.geometry.coordinates[0], d.geometry.coordinates[1]]);
可以简化为:
projection(d.geometry.coordinates);
谢谢,先生。你是救命恩人。