我有一个正在构建的D3地图。我想通过下拉菜单更改地图。下拉列表将确定一个值,并根据该值更改与D3贴图相关的样式。我怎样才能做到这一点?我已经尝试过尽可能简化我的代码,但是我不知道如何使其工作。在我的示例中,如果您从下拉菜单中选择“布朗克斯”,它将使整个地图变为红色;否则应为蓝色。
谢谢!
柱塞:http ://plnkr.co/edit/ouuArH6mgwvcckNZDa1L?p=preview
代码:
<!DOCTYPE html>
<meta charset="utf-8">
<style>
#boroughs {
stroke: #aaa;
stroke-width: 1px;
fill: #ccc;
width
}
</style>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<body>
<select id="filter">
<option>Select A Borough</option>
<option value="Bronx">Bronx</option>
<option value="Brooklyn">Brooklyn</option>
<option value="Manhattan">Manhattan</option>
<option value="Queens">Queens</option>
<option value="Staten_Island">Staten Island</option>
</select>
<script>
var selection;
d3.select('#filter')
.on("change", function () {
var section = document.getElementById("filter");
selection = section.options[section.selectedIndex].value;
});
console.log("selection:", selection);
var width = Math.max(960, window.innerWidth),
height = Math.max(500, window.innerHeight);
var container = d3.select("body").append("div")
.attr("id", "container")
.style("width", width + "px")
.style("height", height + "px");
d3.json("nyc.json", function(error, nyb) {
var projection = d3.geo.mercator()
.center([-73.94, 40.70])
.scale(50000)
.translate([(width) / 2, (height)/2]);
var path = d3.geo.path()
.projection(projection);
var map = container.append("svg")
.attr("id", "boroughs")
.style("width", width + "px")
.style("height", height + "px")
.selectAll(".state")
.data(nyb.features)
.enter().append("path")
.attr("class", function(d){ return d.properties.name; })
.attr("fill", function(d){
if (selection == "Bronx"){ return "#ff0000";}
else { return "#0000ff";}
})
.attr("d", path);
});
</script>
</body>
</html>
给类指定路径,使它们属于下拉框上的该类别:
var map = container.append("svg")
.attr("id", "boroughs")
.style("width", width + "px")
.style("height", height + "px")
.selectAll(".state")
.data(nyb.features)
.enter().append("path")
//this set the class
.attr("class", function(d){ return "state " + d.properties.borough.replace(" ", "_"); })
然后在选择时执行:
d3.select('#filter')
.on("change", function () {
var section = document.getElementById("filter");
selection = section.options[section.selectedIndex].value;
d3.selectAll(".state").style("fill", "blue");//reset all to blue
d3.selectAll("."+selection.replace(" ", "_")).style("fill", "red"); //color the selected index
});
这里的工作代码
希望这可以帮助!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句