我使用 D3.js 和 Leaflet,我想用不同的颜色设置每个圆圈的样式。我有一个函数检查一个变量值,并根据该变量返回该圆圈的填充颜色。在此代码后仅显示一个圆圈,而不是所有数组(点):
map._initPathRoot();
var svg = d3.select("#map").select("svg"),
g = svg.append("g");
var feature = g.selectAll("circle")
.data(points)
.enter().append('svg')
.each(function (d, i) {
d3.select(this).selectAll('circle')
.data([d])
.enter()
.append('circle')
.attr('r', 10)
.attr('stroke', 'white')
.attr('stroke-width', 1)
.attr('opacity', 0.8)
.style('fill', getFeatureColor(d)) //returns "red"
});
map.on("viewreset", update);
update();
function update() {
feature.attr("transform",
function (d) {
if (d !== undefined) {
return "translate(" +
map.latLngToLayerPoint(d.LatLng).x + "," +
map.latLngToLayerPoint(d.LatLng).y + ")";
}
}
)
}
function getFeatureColor(d) {
if(d.count>20) {
return "red";
}
else {return "blue"}
}
最佳答案
我认为,不需要额外的 SVG 元素并迭代数据两次。您可以直接使用点数组创建圆,如下所示。
希望这有帮助。
var feature = g.selectAll("circle")
.data(points)
.enter()
.append('circle')
.attr('r', 10)
.attr('stroke', 'white')
.attr('stroke-width', 1)
.attr('opacity', 0.8)
.style('fill', function(d){ return getFeatureColor(d) });
关于javascript - 如何将 d3.js 选择设置为单个元素的样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37206087/