问题描述
我想使用d3.js和topoJSON创建非洲地图。我有该数据源
i want to create map of Africa using d3.js and topoJSON. I have that datasource https://gist.githubusercontent.com/bricedev/3905007f1794b0cb0bcd/raw/ad5c995f6990f7c3c7fad5c6206bc6fd5462f1fb/africa.json
这是我的代码。如何获得属性和创建正确的地图?请帮助我在哪里错误?
That is my code. How i can get properties and create correct map? Please help me where is the error?
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="D3byEX 12.15" />
<meta charset="utf-8">
</head>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://d3js.org/topojson.v1.min.js"></script>
<script>
var width = 1000, height = 728;
var svg = d3.select("body").append("svg")
.attr({ width: width, height: height });
var mainGroup = svg.append("g");
mainGroup.style({ stroke: "white", "stroke-width": "2px", "stroke-opacity": 0.0 });
var projection = d3.geo.mercator();
var path = d3.geo.path().projection(projection);
var url = 'https://gist.githubusercontent.com/bricedev/3905007f1794b0cb0bcd/raw/ad5c995f6990f7c3c7fad5c6206bc6fd5462f1fb/africa.json';
d3.json(url, function (error, africa) {
var countries = topojson.feature(africa, africa.objects.countries).features;
var neighbors = topojson.neighbors(africa.objects.countries.geometries);
var color = d3.scale.category20();
mainGroup.selectAll("path", "countries")
.data(countries)
.enter().append("path")
.attr("d", path)
.style("fill", function (d, i) {
return color(d.color = d3.max(neighbors[i],
function (n) { return countries[n].color; }) + 1 | 0);
});
mainGroup.selectAll("path")
.on("mouseover", function () {
console.log("mouseover");
d3.select(this).style("stroke-opacity", 1.0);
});
mainGroup.selectAll("path")
.on("mouseout", function () {
d3.select(this).style("stroke-opacity", 0.0);
});
});
</script>
推荐答案
您的topojson不在WGS84中,也就是说,纬度/长坐标空间或未投影的数据。 D3.projection()需要WGS84。
Your topojson is not in WGS84, that is to say lat/long coordinate space or unprojected data. D3.projection() requires WGS84.
您的topojson已经投影,我假设是投影。您不需要使用投影在d3.js中显示此内容。为了显示这个没有投影的数据,你可以定义geoPath的投影为:
Your topojson is already projected in, what I assume is, the Africa Lambert Conformal Conic projection. You do not need to use a projection to display this in d3.js. In order to display this data without a projection you can define the projection of your geoPath as:
path = d3.geoPath().projection(null);
这是topojson在。
This is how the topojson was projected in the block in which that data came from.
如果需要缩放或翻译投影,那么d3.geoTransform可以帮助您,请参见。
If you need to scale or translate the projection, then d3.geoTransform can help you, see this block.
或者,您可以重新输入topojson,使其使用lat / long对,并使用d3.projection()进行正确投影。
Alternatively, you can reproject your topojson so that it uses lat/long pairs and will properly project using d3.projection().
这篇关于使用d3.js和topoJSON创建非洲地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!