【发布时间】:2015-05-25 00:43:49
【问题描述】:
我已经设置了一个示例来演示我遇到的问题:
简而言之,我正在使用 d3 渲染美国地图。我正在附加相关的数据属性来处理点击事件并确定被点击的状态。
点击事件会执行以下操作:
-
我正在获取美国县 topojson 文件(其中包含 ALL US 县)。
从数据中删除不相关的县并将它们呈现在 被点击的州的地图。
我似乎无法弄清楚幕后发生了什么导致一些县被绘制而其他县被忽略。
当我记录从过滤列表返回的数据时,我会显示准确的县数,但它们只是部分绘制在地图上。有些州不返回任何东西。 宾夕法尼亚州和德克萨斯州部分有效。
我检查了数据和比较操作,但我认为这可能与弧属性不匹配有关。
如果我使用 Counties JSON 文件来渲染整个美国地图,它们都会出现。
如果有人可以帮助阐明可能发生的事情,那就太好了。
svg {
fill:#cccccc;
height:100%;
width:100%;
}
.subunit{
outline:#000000;
stroke:#FFFFFF;
stroke-width: 1px;
}
.subunit:hover{
fill:#ffffff;
stroke:#FFFFFF;
stroke-width="10";
}
<body>
<script src="http://www.cleanandgreenfuels.org/jquery-1.11.3.min.js"></script>
<script src="http://www.cleanandgreenfuels.org/d3.v3.min.js"></script>
<script src="http://www.cleanandgreenfuels.org/topojson.v1.min.js"></script>
<script>
var width = window.innerWidth;
height = window.innerHeight;
var projection = d3.geo.albers()
.scale(1500)
.translate([width / 2, height / 2]);
//d3.geo.transverseMercator()
//.rotate([77 + 45 / 60, -39 - 20 / 60]);
//.rotate([77+45/60,-40-10/60])
//.scale(500)
//.translate([width / 2, height / 2]);
var path = d3.geo.path()
.projection(projection);
var svg = d3.select("body").append("svg")
.attr("width", width+"px")
.attr("height", height+"px");
d3.json("http://www.cleanandgreenfuels.org/usstates2.json.php", function(error, us, init) {
//svg.append("path")
// .datum(topojson.feature(us, us.objects.counties))
//.attr("d", path);
function init(){
$( document ).ready(function() {
$('.subunit').on('click',function(){
var stateid = $(this).attr("data-stateid");
function clearStates(stateid){
d3.json("http://www.cleanandgreenfuels.org/uscounties2.json.php", function(error, us) {
console.log(us);
console.log("DATA CLICKED ID "+stateid);
test = jQuery.grep(us.objects.counties.geometries, function(n){
return (n.properties.stateid == stateid);
});
us.objects.counties.geometries = test;
console.log(test.length);
console.log(us.objects.counties.geometries.length);
var test = topojson.feature(us, us.objects.counties).features;
console.log(test);
console.log(test.length);
svg.selectAll(".subunit")
.data(test)
.enter().append("path")
.attr("class", function(d) { return "subunit"; })
.attr("d", path)
.attr("data-countyid", function(r){ return r.id; });
});
}
clearStates(stateid);
});
});
}
svg.selectAll(".subunit")
.data(topojson.feature(us, us.objects.us).features)
.enter().append("path")
.attr("class", function(d) { return "subunit"; })
.attr("d", path)
.attr("data-stateid", function(r){ return r.id; });
init();
});
</script>
</body>
【问题讨论】:
-
我发现这个资源bl.ocks.org/mbostock/4108203 似乎提供了更好的实现。尽管简单的解决方案是更好地构造输入的数据,但我仍然很好奇上面的示例发生了什么。
标签: javascript jquery d3.js geojson topojson