【发布时间】:2017-12-14 18:04:45
【问题描述】:
我正在尝试让世界地图显示类似于此处提供的美国地图 (U.S. map),但我遇到了一些问题。目前,这就是我迄今为止的世界地图代码:
<!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/world-atlas@1/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/world-atlas@1/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>
我相信我的缩放比例错误并且没有正确地投影到地图上。如果有人有任何关于我是如何做到的,请告诉我。
【问题讨论】: