경주 d3.js topoJson 그래프
-
22-12-2019 - |
문제
나는 그리고 지도를 사용하여 topoJson 그래서 내가 다음에 이 예제
그러나 나는 못하고 아무 것도 그려집니다.
여기에 내가 쓴
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<style>
path {
fill: #ccc;
stroke: #fff;
stroke-width: .5px;
}
path:hover {
fill: red;
}
</style>
</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 = 960,
height = 500;
var path = d3.geo.path();
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
d3.json("tunisia.json", function(error, topology) {
console.log(topology);
svg.selectAll("path")
.data(topojson.feature(topology, topology.objects.governorates).features)
.enter().append("path")
.attr("d", path);
});
</script>
</body>
</html>
후에 디버깅 이 경로에 케이스가 다음과 같다:
<svg width="960" height="500">
<path></path>
<path></path>
</svg>
반면 그것은 일반적으로 다음과 같다:
<svg width="960" height="500">
<path d="M183.85631949544694,17.16574961388676L184.64695256075555,18.261986556132797L184.24437929962187,21.436416964644536L184.9109502450185,22.72190753660925L183.42733139583214,23.600229178621248L181.43637647772152,23.38526266060535L162.4858998398068,18.04698631290296L162.95134674943927,16.322885588815097L161.24381018256219,15.20848145955324L160.04585728433227,11.701769628478132L161.0879861841512,10.793553936506555L172.9773901748378,14.256236175137701Z"></path>
</svg>
여기에는 데이터 사용:https://raw.githubusercontent.com/mtimet/tnacmaps/master/topojson/tunisia.json
할 수 있을 확인하시기 바랍 내가 뭘 잘못된
해결책
에 문제가 없 json 파일입니다.
문제 있는지 정의를 위한 투상을 당신 d3.geo.path()
즉 그것은 다시 기본입니다.에 따라 설명서 링크:
#d3.geo.path()
새로 만들고 지리적인 경로로 발전기를 가진 기본 설정:이 albersUsa 프로젝션 및 포인트의 반경 4.5 픽셀이 있습니다.
귀하의 지리적 데이터에 대한 지도의 튀니지,그래서 albersUsa 투사이 들어있지 않아의 좌표가에서 당신의합니다.그 이유는 경로는 데이터는 빈에서 출력됩니다.
이 문제를 해결하려면,당신은 정의할 필요가 투영합니다.면 이 작업을 수행할 수 있습니다 당신은 데이터를 로드할 수 있습 사용 d3.geo.bounds()
, 전달,당신 featureCollection
을 찾기 위해 지리적 경계의합니다.
var featureCollection = topojson.feature(topology, topology.objects.governorates);
var bounds = d3.geo.bounds(featureCollection);
그런 다음 이러한 경계선을 계산할 수 있습의 중심 featureCollection:
var centerX = d3.sum(bounds, function(d) {return d[0];}) / 2,
centerY = d3.sum(bounds, function(d) {return d[1];}) / 2;
다음 사용할 수 있습니다 이를 중심의 투영합니다.예를 들어,사용하는 경우 메르카토르 투,다음 작업을 수행할 수 있습니다:
var projection = d3.geo.mercator()
.scale(3000)
.center([centerX, centerY]);
의 선택의 규모 3000 은 임의로,그것은 단지 잘 작동하는 듯 이 경우 조정하든 당신을 위해 작동합니다.
마지막으로,당신은 필요 설정 .projection()
의 path
을 투영을 실제로 전에 만들기 svg 경로입니다.
path.projection(projection);
svg.selectAll("path")
.data(featureCollection.features)
.enter().append("path")
.attr("d", path);
기 는 작업을 사용하여 예를 들어 있습니다.