我正在用 D3 和 topojson 過濾掉美國縣的一個子集。我可以成功過濾掉縣并將它們繪制到 SVG 元素,但是如何更改地圖邊界以適應新選擇的縣?它正在渲染地圖,就好像邊界是所有美國縣,而只是過濾的縣。
var width=960,
height=600,
centered;
const svgElement = d3.select(ref.current)
.append("svg")
.attr("preserveAspectRatio", "xMinYMin meet")
.attr("viewBox", [0,0,width,height]);
var path = d3.geoPath();
d3.json("https://d3js.org/us-10m.v2.json").then((d) => {
d.objects.counties.geometries = d.objects.counties.geometries.filter(function(item) {
return props.data.indexOf(item.id) > -1
})
var counties = topojson.feature(d, d.objects.counties).features;
svgElement.append("g")
.attr("class", "filled-territory")
.selectAll("path")
.data(counties)
.enter()
.append("path")
.attr("d", path)
});
props.data一系列縣 ID在哪里,例如 -
[
"45001",
"45003",
"45007",
"45083",
"45087",
"45091"
]
我可以讓它像這樣顯示,但我不知道如何讓路徑填充 SVG:

uj5u.com熱心網友回復:
這個特定的檔案使用像素坐標系(它是投影的地理資料),它填充了 [0,0] 和 [960,600] 之間的范圍。因為它使用這個坐標系,所以通常我們可以使用 d3.geoPath 的默認投影,這是一個將 json 中的坐標視為像素的空投影。但是,geoPath 本身并不能提供一種將要素居中或縮放的方法。
D3 地理投影帶有一種稱為 fitSize(也稱為 fitExtent 或其他)的方法,該方法采用 geojson物件并設定投影比例并將屬性轉換為在指定范圍內將該 geojson 物件居中。由于我們已經有投影資料,我們可以使用 d3.geoIdentity() ,它提供了一些方便的投影方法,如 fitSize 但不投影我們的資料,因為它已經投影了。
為了使用 fitSize 我們可以使用以下內容:
// get a geojson feature collection object:
var geojson = topojson.feature(d, d.objects.counties)
// create a geoidentity "projection" and center the geojson:
var projection = d3.geoIdentity()
.fitSize([width,height],geojson)
// set the path's projection:
path.projection(projection);
// Now access the array of features in the collection for use with .data():
var counties = geojson.features;
看起來像:
顯示代碼片段
var data = [
"45001",
"45003",
"45007",
"45083",
"45087",
"45091"
]
var width=500,
height=500;
const svgElement = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height);
var path = d3.geoPath();
d3.json("https://d3js.org/us-10m.v2.json").then((d) => {
d.objects.counties.geometries = d.objects.counties.geometries.filter(function(item) {
return data.indexOf(item.id) > -1
})
var geojson = topojson.feature(d, d.objects.counties)
var projection = d3.geoIdentity()
.fitSize([width,height],geojson)
path.projection(projection);
var counties = geojson.features;
svgElement.append("g")
.attr("class", "filled-territory")
.selectAll("path")
.data(counties)
.enter()
.append("path")
.attr("d", path)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/topojson/3.0.2/topojson.min.js
"></script>
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/326006.html
標籤:javascript d3.js 拓扑文件
上一篇:使用d3強制網路適合邊界框
