javascript - 使用 d3.geoPath(projection) 似乎没有将正确的属性“d”添加到“路径”中
问题描述
我正在尝试为一个项目创建美国地图。为此,我将d3.geoAlbersUsa()
其用作投影和d3.geoPath(projection)
路径功能。但是,当将“路径”附加到我的 svg 时,看起来“d”属性没有设置。
// Projection from geoAlbersUsa
let projection = d3.geoAlbersUsa()
.translate(width/2,height/2)
.scale(10000);
// Path from geoPath with the previous projection
let path = d3.geoPath().projection(projection);
let svg = d3.select("#svg");
// Load in csv and json data
d3.csv("state_results.csv", data => {
d3.json("states.json", json => {
// Process data from csv file and json file
...
...
...
// Selecting 'g' element in svg and appending 'path'
d3.select("#map").selectAll("path")
.data(json.features)
.enter()
.append("path")
.attr("d", path)
.style("fill", d => {
return d.properties.party;
});
当我启动我的服务器时,这就是我检查 svg 元素时显示的内容:
"d"
关于为什么在每条路径中没有正确设置属性的任何想法?
下面是json.features
数组中的一个元素:
{"type":"Feature","id":"49","properties":{"name":"Utah","density":34.30},"geometry":{"type":"Polygon","coordinates":[[[-112.164359,41.995232],[-111.047063,42.000709],[-111.047063,40.998429],[-109.04798,40.998429],[-109.053457,39.125316],[-109.058934,38.27639],[-109.042503,38.166851],[-109.042503,37.000263],[-110.499369,37.00574],[-114.048427,37.000263],[-114.04295,41.995232],[-112.164359,41.995232]]]}},
解决方案
我已经使它与您提供的示例数据一起工作。您需要在 中的数字周围加上括号.translate([width / 2, height / 2])
。除此之外,我只需要将比例缩小一点以使其适合屏幕。
const jsonFeatures = [{
"type": "Feature",
"id": "49",
"properties": {
"name": "Utah",
"density": 34.30
},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[-112.164359, 41.995232],
[-111.047063, 42.000709],
[-111.047063, 40.998429],
[-109.04798, 40.998429],
[-109.053457, 39.125316],
[-109.058934, 38.27639],
[-109.042503, 38.166851],
[-109.042503, 37.000263],
[-110.499369, 37.00574],
[-114.048427, 37.000263],
[-114.04295, 41.995232],
[-112.164359, 41.995232]
]
]
}
}];
let width = 500,
height = 300;
// Projection from geoAlbersUsa
let projection = d3.geoAlbersUsa()
.translate([width / 2, height / 2])
.scale(1000);
// Path from geoPath with the previous projection
let path = d3.geoPath().projection(projection);
let svg = d3.select("svg").attr("width", width).attr("height", height);
svg.selectAll("path")
.data(jsonFeatures)
.enter()
.append("path")
.attr("d", path)
.style("fill", d => {
return d.properties.party;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.js"></script>
<svg></svg>
推荐阅读
- python - 如何使用 Panda 将 JSON 字符串中的所有元素输出到表中
- python - 将总值的百分比插入到熊猫的数据透视表中
- reactjs - 是什么意思
in '导出默认类 App 扩展组件 ' 当我使用 react-native 创建项目时 - database - 可序列化隔离级别的有效案例
- javascript - 使用 Redux 将 onChangeText 中的 TextInput 格式化为 React Native 中的美元金额
- c# - 如何将 DataTable 转换为 CustomDataTable?
- node.js - 如何使用节点 js 将 azure blob 存储中的文件下载到本地文件夹
- blockchain - 你能告诉我如何使用 InvokeScriptTransaction
- javascript - 每次连续构建时,Webpack 包的大小都会增加
- windows - 无法在 Windows 10 上成功安装 rust