I am trying to draw rectangles on different map projections using d3.js and geojson. The mapped coordinates seem right, however the edges appear curved in a strange way. I understand that this may have to do with the shortest path on the real Earth, but what I would like is that the edges follow the parallels/meridians graticule of the projection. Is there a way to do that? Can anyone help?
Example: Aitoff Projection
Example: Mercator
Here is the code I am using:
<!DOCTYPE html>
<html>
<head>
<title>World Map</title>
<meta charset="utf-8">
<script src="https://d3js.org/d3-geo-projection.v2.min.js"></script>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/topojson.v2.min.js"></script>
<style>
path {
fill: red;
stroke: #000;
stroke-width: .1px;
}
.graticule {
fill: none;
stroke: #000;
stroke-width: .2px;
}
.foreground {
fill: none;
stroke: #333;
stroke-width: 1.2px;
}
</style>
</head>
<body>
<svg width="960" height="600"></svg>
<script>
const svg = d3.select("svg")
const myProjection = d3.geoMercator()
const path = d3.geoPath().projection(myProjection)
const graticule = d3.geoGraticule()
const geojson = {
"type": "FeatureCollection",
"features": [
{ "type": "Feature", "properties": {
"color": "blue"
},
"geometry": {
"type": "Polygon",
"coordinates": [[[-80.0, 50.0], [-20.0, 50.0], [-20.0, -10.0], [-80.0, -10.0], [-80.0, 50.0]]]
} }
]
}
function drawMap(err, world) {
if (err) throw err
svg.append("g")
.selectAll("path")
.data(topojson.feature(world, world.objects.land).features)
.enter().append("path")
.attr("d", path);
svg.append("path")
.datum(graticule)
.attr("class", "graticule")
.attr("d", path);
svg.append("path")
.datum(graticule.outline)
.attr("class", "foreground")
.attr("d", path);
svg.append("g")
.selectAll("path")
.data(geojson.features)
.enter().append("path")
.attr("d", path)
}
d3.json("https://unpkg.com/[email protected]/world/50m.json", drawMap)
</script>
</body>
</html>
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…