1
我正在嘗試編寫一個通用地圖,以便任何新的csv都會更改數據可視化。我能夠繪製地圖,使用geojson加入csv,甚至在mouseover上打印csv數據。但是,當我嘗試使用這些數據將顏色應用於地圖時,我始終得到undefined
- 我猜是由於js的異步性質。我怎樣才能最有效地解決這個問題?結合geojson和csv,然後使用新數據來設計地圖樣式
這裏是我的代碼:
// Community colors
var comm_colors = [ "red", "blue", "green", "yellow", "purple" ];
// CSV
function parse_add_csv(cts){
var new_cts = cts
console.log('parsing csv');
d3.csv("data/communities.csv", function(comms)
{ csv = comms.map(function(d)
{
return {"community": d.community, "label": d.BoroCT2010} ;
})
csv.forEach(function(d, i) {
new_cts.forEach(function(e, j) {
if (d.label === e.properties.BoroCT2010) {
e.properties.community = parseInt(d.community)
}
})
})
})
return new_cts
}
d3.json("data/nyct2010_17a3_topo.json", function(error, nyb) {
console.log('tracts uploaded, v3')
var ctss = topojson.feature(nyb, nyb.objects.nyct2010_17a3).features;
ctss = parse_add_csv(ctss); // match data from csv by BoroCT2010
cts.selectAll(".tract")
.data(ctss)
.enter().append("path")
.attr("class", "tract")
.attr("d", path)
.attr("id", function(d) {
return d.properties.BoroCT2010;})
.attr("nhd_name", function(d) {
return d.properties.NTAName;})
.style('fill', function(d){
console.log(comm_colors[d.properties.community])
return comm_colors[d.properties.community];})
.on("mouseover", handleMouseOver)
.on("mouseout", handleMouseOut)
.style('fill', function(d) {return
comm_colors[d.properties.community]});
})
在這裏,我想從CSV匹配的社區列到GeoJSON的,然後用它來從列表中選擇一種顏色。它完美,當我打印彩色的鼠標懸停事件,但鏈中不起作用:
.style('fill', function(d){
console.log(comm_colors[d.properties.community])
return comm_colors[d.properties.community];})