我正在尝试绘制英国 map 并在其上绘制一些选定的点。 我正在关注本教程的第一部分 https://bost.ocks.org/mike/map/
这就是我所做的。
var svg = d3.select('body').append('svg')
.attr('height', height)
.attr('width', width)
.call(zoom);
d3.json("/data/uk.json", function(error, uk) {
if (error) return console.error(error);
var subunits = topojson.feature(uk, uk.objects.subunits);
var projection = d3.geo.albers()
.center([0, 55.4])
.rotate([4.4, 0])
.parallels([50, 60])
.scale(6000)
.translate([width / 2, height / 2]);
var path = d3.geo.path()
.projection(projection);
svg.append('path')
.datum(subunits)
.attr('d', path);
svg.selectAll('.subunit')
.data(topojson.feature(uk, uk.objects.subunits).features)
.enter().append('path')
.attr('d', path);
这是我尝试绘制点的部分
d3.json('/data/places.json', function (error , result) {
if(error)
console.error(error);
svg.append('path')
.data(result.features)
.style('stroke', 'green')
.attr('d' , d3.geo.path().projection(projection))
});
上面的代码仅在 map 上绘制一个点,即 JSON 文件中的第一个点
最佳答案
您在使用时没有正确绑定(bind)您的功能数据
svg.append('path')
.data(result.features)
.style('stroke', 'green')
.attr('d' , d3.geo.path().projection(projection))
这将附加一个路径,将 result.features
的第一个元素绑定(bind)到该路径,并相应地设置样式和属性。
要按照您想要的方式工作,您需要使用 data joining D3的机制。
svg.selectAll('path.features')
.data(result.features)
.enter().append('path')
.attr('class', 'feature')
.style('stroke', 'green')
.attr('d' , d3.geo.path().projection(projection))
这将计算 data join对于 result.features
中的功能,将新元素放入输入选择中,可通过调用 enter()
访问该选择关于选择。使用此输入选择,您现在可以附加所有功能的路径。
与您的问题不直接相关的进一步附注:
根据您想要附加到 map 的要素数量,.attr("d")
setter 可能会被频繁调用。您可以通过重用路径生成器的一个实例来提高性能:
var geoPath = d3.geo.path().projection(projection); // You need just one instance
svg.selectAll('path.features')
.data(result.features)
.enter().append('path')
.attr('class', 'feature')
.style('stroke', 'green')
.attr('d' , geoPath) // Re-use the path generator
这被认为是最佳实践,应该普遍应用。
关于javascript - d3.path 仅绘制特征集合的第一个特征,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41181193/