我想获得一张世界地图,显示类似于这里提供的美国地图(U.S. map),但我遇到了一些问题。目前,这是我迄今为止我的世界地图代码:d3.js world topojson v4
<!DOCTYPE html>
<style>
</style>
<svg width="960" height="600"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/topojson.v2.min.js"></script>
<script>
var svg = d3.select("svg");
var path = d3.geoPath();
d3.json("https://unpkg.com/[email protected]/world/50m.json", function(error, world)
{
if (error) throw error;
svg.append("g")
.selectAll("path")
.data(topojson.feature(world, world.objects.countries).features)
.enter().append("path")
.attr("d", path);
});
</script>
然而,它显示只占用了我的窗口的左上部分,而且似乎看不正确的地图。 目前我对我可能做错了什么感到困惑。如果有人有任何见解,我将不胜感激。
谢谢。
编辑:实际上,我是能够得到它提供的代码在这里工作
<!DOCTYPE html>
<style>
.countries :hover
{
fill: red;
}
.country-borders
{
fill: none;
stroke: #FFF;
stroke-width: 0.5px;
stroke-linejoin: round;
stroke-linecap: round;
cursor: pointer;
}
</style>
<meta charset="utf-8">
<body>
<script src="http://d3js.org/d3.v4.min.js"></script>
<script src="http://d3js.org/topojson.v1.min.js"></script>
<script>
var format = d3.format(",");
var margin = {top: 0, right: 0, bottom: 0, left: 0},
width = 1200 - margin.left - margin.right,
height = 900 - margin.top - margin.bottom;
var path = d3.geoPath();
var svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height)
.append('g')
.attr('class', 'map');
var projection = d3.geoMercator()
.scale(170)
.translate([width/2, height/1.5]);
var path = d3.geoPath().projection(projection);
d3.json("https://unpkg.com/[email protected]/world/50m.json", function(error, world)
{
svg.append("g")
.attr("class", "countries")
.selectAll("path")
.data(topojson.feature(world, world.objects.countries).features)
.enter().append("path")
.attr("d", path);
svg.append("path")
.attr("class", "country-borders")
.attr("d", path(topojson.mesh(world, world.objects.countries, function(a, b)
{
return a !== b;
})));
});
</script>
</body>
</html>
我相信我在做我的缩放错误,不能正确地做投影到地图上。如果有人对我的做法有任何意见,请让我知道。