当我在SVG元素中绘制百慕大三角形时,尺度不是我所期望的(三角形应该延伸到框的边缘)并且填充是向后的(而不是绘制三角形,它绘制一个带有三角形切边的正方形)。
var geojson = {
"features": [
{
"type": "Feature",
"properties": {
"name": "Bermuda Triangle",
"area": 1150180
},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[-64.73, 32.31],
[-80.19, 25.76],
[-66.09, 18.43],
[-64.73, 32.31]
]
]
}
}
],
"type":"FeatureCollection"
};
var width = 480;
var height = 480;
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.attr("style", "border: 2px solid black");
var projection = d3.geoMercator().fitSize([width, height], geojson);
var path = d3.geoPath().projection(projection);
svg.selectAll('path')
.data(geojson.features)
.enter()
.append('path')
.attr('d', path)
.style("fill", "red")
.style("stroke-width", "1")
.style("stroke", "black");

<script src="//d3js.org/d3.v4.js"></script>
&#13;
我做错了什么?
答案 0 :(得分:6)
让我们改变一下:
[
[-64.73, 32.31],
[-80.19, 25.76],
[-66.09, 18.43],
[-64.73, 32.31]
]
对此:
[
[-64.73, 32.31],
[-66.09, 18.43],
[-80.19, 25.76],
[-64.73, 32.31]
]
这似乎是一个小变化,但它是一个重要的变化:D3期望多边形顶点以顺时针顺序。
根据API:
球面多边形还需要一个缠绕顺序约定来确定多边形的哪一边是内部:小于半球的多边形的外环必须顺时针,而多边形的外环大于一个半球必须是逆时针的。 (强调我的)
此外,这是由Bostock(D3创作者)制作的一个有趣的bl.ocks,在教导中解释了您的问题:https://bl.ocks.org/mbostock/a7bdfeb041e850799a8d3dce4d8c50c8
以下是您更改的代码(以及删除fitSize
):
var geojson = {
"features": [{
"type": "Feature",
"properties": {
"name": "Bermuda Triangle",
"area": 1150180
},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[-64.73, 32.31],
[-66.09, 18.43],
[-80.19, 25.76],
[-64.73, 32.31]
]
]
}
}],
"type": "FeatureCollection"
};
var width = 480;
var height = 480;
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.attr("style", "border: 2px solid black");
var projection = d3.geoMercator();
var path = d3.geoPath().projection(projection);
svg.selectAll('path')
.data(geojson.features)
.enter()
.append('path')
.attr('d', path)
.style("fill", "red")
.style("stroke-width", "1")
.style("stroke", "black");
&#13;
<script src="//d3js.org/d3.v4.js"></script>
&#13;
答案 1 :(得分:0)
如果有人会遇到类似的问题,我创建了一个工具,该工具可以帮助您倒回或反转geojson
它帮助我轻松地对一些geoJson文件进行了更改
https://observablehq.com/@bumbeishvili/rewind-geojson
您可以仅将其作为摘要运行
<div class="notebook-content">
</div>
<script type="module">
import notebook from "https://api.observablehq.com/@bumbeishvili/rewind-geojson.js"; // "download code" url
document.querySelector('.notebook-content').innerHTML =notebook.modules[0].variables
.filter(d=>d)
.map((d,i)=>` <div class=" observable-wrapper div-number-${i}"></div>`)
.join('')
.concat('<div style="display:none" class="hidden"></div>')
import {Inspector, Runtime} from "https://unpkg.com/@observablehq/runtime@3/dist/runtime.js";
let i=1;
Runtime.load(notebook, (variable) => {
if(i==4 ){i++; return new Inspector(document.querySelector(`.hidden`));}
if(i==13)return;
return new Inspector(document.querySelector(`.observable-wrapper:nth-child(${i++})`));
});
</script>