我正在加载一个GeoJSON数据文件,其中包含一个对象数组,每个对象都包含不同国家轮廓的向量信息。将相同的数组元素绑定到每个DOM元素。我以前在JavaScript中遇到过这个作用域问题,但我所做的每一次更改都没有导致加载任何内容。
我附加了一个jsfiddle。我使用了一个示例数据文件,它似乎需要几秒钟才能加载。
我的jsfiddle代码如下所示:
$(document).ready(function() {
d3.json(
"https://raw.githubusercontent.com/datasets/geo-boundaries-world-110m/master/countries.geojson",
function(error, data) {
var myGeoJSON = data.features;
for (i = 0; i < myGeoJSON.length; i++) {
var path = d3.geo.path();
var width = 960;
var height = 600;
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
svg.selectAll("path")
.data(data.features)
.enter().append("path")
.attr("d",path)
.attr("fill","#3e429a");
}
}
);
});
发布于 2015-10-12 12:34:41
您不需要遍历功能数组。您的数据文件是一个FeatureCollection,它可以D3 can draw为单个path元素:
svg.append("path").datum(data).attr("d", d3.geo.path());
或者作为单独的路径元素,每个功能(国家/地区)对应一个:
svg.selectAll("path").data(data.features)
.enter().append("path").attr("d", d3.geo.path())
默认情况下,D3使用投影d3.geo.albersUsa()
,它将夏威夷带到墨西哥,将阿拉斯加带到热带之外。您可以切换到equirectangular projection查看整个世界:
d3.json(
"https://raw.githubusercontent.com/datasets/geo-boundaries-world-110m/6cf0946a0f4d027d21686e8402f19b524c4f6385/countries.geojson",
function(error, data) {
var projection = d3.geo.equirectangular();
var path = d3.geo.path().projection(projection);
var width = 960;
var height = 600;
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
svg.selectAll("path")
.data(data.features)
.enter().append("path")
.attr("d", path)
.attr("fill", "#3e429a");
}
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
结语:我最初尝试使用更常见的Mercator projection,结果却发现它是it cannot handle Antarctica。D3绘制大陆的形状,然后填充其余的海洋。
在同一个D3论坛线程中,D3 mentioned a bug in the TopoJSON tool的作者过去常常生成地图,因此您使用的数据文件可能会出现问题。如果您更喜欢墨卡托,您可能需要与geo-boundaries-world-110m的维护者合作来修复数据文件,或者只是从您的地图中排除南极洲。
墨卡托的南极洲演示:
d3.json(
"https://raw.githubusercontent.com/datasets/geo-boundaries-world-110m/6cf0946a0f4d027d21686e8402f19b524c4f6385/countries.geojson",
function(error, data) {
var projection = d3.geo.mercator();
var path = d3.geo.path().projection(projection);
var width = 960;
var height = 600;
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var antarctica = data.features.splice(6, 1);
// now "data" has the rest of the world
svg.selectAll("path")
.data(antarctica)
.enter().append("path")
.attr("d", path)
.attr("stroke", "red").attr("stroke-width", 10)
// thick borders so we can see the odd paths
.attr("fill", "#3e429a");
}
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
https://stackoverflow.com/questions/32903210
复制相似问题