我想根据县数据创建美国地图。我正在使用这个 JSON 拓扑数据来创建图表:https://cdn.freecodecamp.org/testable-projects-fcc/data/choropleth_map/counties.json
在第一步中,我像这样创建了地图,并且工作正常:
var path = d3.geoPath();
svgContainer.selectAll("path")
.data(topojson.feature(countyData, countyData.objects.counties).features)
.enter()
.append("path")
.attr("d", path)
Picture: US map renders OK but too large
但是,它对于我的目的来说太大了,所以我试图缩小它。我尝试了在其他几个项目中看到的 projections
(例如:https://www.d3-graph-gallery.com/graph/choropleth_basic.html)。不幸的是,它只是呈现一个黑色矩形。我还尝试了 geoAlbersUsa() 和其他一些预测,但没有帮助。如何使地图数据按比例缩放?
var projection = d3.geoAlbersUsa() // geoMercator() also does not work
.scale(200)
.translate([width / 2, height / 2]);
var path = d3.geoPath().projection(projection);
svgContainer.selectAll("path")
.data(topojson.feature(countyData, countyData.objects.counties).features)
.enter()
.append("path")
.attr("d", path)
Picture: projection renders black rectangle
我在这里做错了什么?
答案 0 :(得分:1)
在第二个代码块中一切看起来都很好(使用 d3.geoAlbersUSA()),但我认为你用 .scale(200) 放大得太近了,只能看到一个县的中部。如本文所述,如果您以较小的比例值缩小,您可能会开始看到更多地图。(What does it mean to scale a projection in d3?) 您最好使用 .fitSize() 而不是 .scale ,因为您似乎试图将整个 topojson 数据集放入一个区域内,而不是放大其中的一部分。使用可变边距更新了下面的示例。
var margin = 20; //amount of whitespace you want around the map
var projection = d3.geoAlbersUsa()
.translate([width / 2, height / 2]);
var path = d3.geoPath().projection(projection);
var countiesFeatureCollection = topojson.feature(countyData, countyData.objects.counties);
//make the map projection fit into size of screen minus margin on all sides
projection.fitSize([width - margin*2, height - margin*2], countiesFeatureCollection);
svgContainer.selectAll("path")
.data(countiesFeatureCollection.features)
.enter()
.append("path")
.attr("d", path)