2017-01-22 23 views
0

這是一個國家的一個簡單而又鼓舞人心的topojson:動態項目單縣

https://bl.ocks.org/mbostock/7061976

它是由一個JSON只包含狀態數據得出如下:

d3.json("va-counties.json", function(error, topo) { 
    if (error) throw error; 

我想要做的是動態投影一個縣。假設有一個鍵盤事件或者某個運行這個功能的函數:讀入解析的數據,找到縣的id,然後返回該縣的topojson特徵。上述塊和我的情況之間的區別在於,我的json文件將包含美國的所有縣,但我一次只需要1個縣。有沒有辦法在D3中實現這一點?

就像一個簡單的試金石,全縣ID = 1000,我想:

var current_county = topojson.feature(topo, topo.objects.counties).filter(function(d) { return d.id=1000;})), 
     bounds = path.bounds(county); 

但我一直得到持續性的錯誤,不管我有多麼辛苦吧。或者它會停止拋出錯誤,但仍然不能「工作」。也許.filter()不是工作的最佳工具?還有其他意見嗎?

感謝您閱讀

回答

4

那麼首先你所有filter語法是錯誤的,我認爲你的意思的比較,而不是分配:

d.id === 1000 

其次,topojson.feature返回GeoJSON的這一個對象,它不會像那樣過濾。最好的辦法是在對其進行過濾的方式:

// filter the geometries of the topojson the structure you want 
var geoCounty = topo.objects.counties.geometries.filter(function(d){ 
    return d.id === "51750"; 
}); 

// assign it back to the topojson object 
topo.objects.counties.geometries = geoCounty; 

// and off you go... 
var county = topojson.feature(topo, topo.objects.counties), 
    bounds = path.bounds(county); 

完全跑步代碼:

<!DOCTYPE html> 
 
<meta charset="utf-8"> 
 
<style> 
 

 
.county { 
 
    fill: #ccc; 
 
} 
 

 
</style> 
 
<body> 
 
<script src="//d3js.org/d3.v3.min.js"></script> 
 
<script src="//d3js.org/d3.geo.projection.v0.min.js"></script> 
 
<script src="//d3js.org/topojson.v1.min.js"></script> 
 
<script> 
 

 
var width = 500, 
 
    height = 300; 
 

 
var projection = d3.geo.conicConformal() 
 
    .parallels([38 + 02/60, 39 + 12/60]) 
 
    .rotate([78 + 30/60, 0]) 
 
    .scale(200000) 
 
    .translate([0, 0]); 
 

 
var path = d3.geo.path() 
 
    .projection(projection); 
 

 
var svg = d3.select("body").append("svg") 
 
    .attr("width", width) 
 
    .attr("height", height); 
 

 
d3.json("https://jsonblob.com/api/ce96ca06-e1ce-11e6-90ab-03e5986c4e20", function(error, topo) { 
 
    if (error) throw error; 
 

 
    var geoCounty = topo.objects.counties.geometries.filter(function(d){ 
 
    return d.id === "51750"; 
 
    }); 
 

 
    topo.objects.counties.geometries = geoCounty; 
 

 
    var county = topojson.feature(topo, topo.objects.counties), 
 
     bounds = path.bounds(county); 
 

 
    projection 
 
     .translate([width/2 - (bounds[0][0] + bounds[1][0])/2, height/2 - (bounds[0][1] + bounds[1][1])/2]); 
 

 
    svg.append("path") 
 
     .datum(county) 
 
     .attr("class", "county") 
 
     .attr("d", path); 
 

 
}); 
 

 
</script>

+0

這使得現在這麼多大意義。謝謝你讓我看到正確的約定。你說得對,我應該使用比較'==='。我正在嘗試測試您的示例,但我在指定庫時遇到了問題。我一直收到「錯誤:無效或意外的令牌。」來自d3.projection.js文件。我知道D3.js是utf-8,是不是有點不同?我該怎麼辦?? –

+0

@ArashHowaida,錯誤消息應該指向你的一行代碼。當你檢查它看起來有什麼東西嗎?錯誤是來自'd3.projection.js'還是你的代碼?我不可能在沒有重現的情況下爲你調試它。 – Mark

+0

它說'd3js.org/d3.geo.projection.v0.min.js'行1,而不是從主html。讓我運行一些測試,看看它是什麼編碼。 –