一.效果图
使用D3来制作中国地图主要有几个地方需要注意:
- 需要用到投影函数,并挂在在路径生成器上。
- 由于同源策略限制的原因,需要通过服务器来返回地图文件,比如
china.json
这种。 - 如果需要做渐变色渲染或者显示标注,需要额外的数据,并通过服务器返回。
- 要区分开
topojson
和geojson
两种格式的数据的不同,他们的加载模式也有所不同,相对于geojson
数据,topojson
文件更小,渲染时更节省Dom空间。
二.代码示例
我把代码部分分为前端和后端,咱们先看前端的部分。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>topojsonMAP</title>
<style>
/* Tooltip CSS */
.d3-tip {
line-height: 1.5;
font-weight: 400;
font-family: "avenir next", Arial, sans-serif;
padding: 6px;
background: rgba(0, 0, 0, 0.6);
color: #FFA500;
border-radius: 1px;
pointer-events: none;
}
/* Creates a small triangle extender for the tooltip */
.d3-tip:after {
box-sizing: border-box;
display: inline;
font-size: 8px;
width: 100%;
line-height: 1.5;
color: rgba(0, 0, 0, 0.6);
position: absolute;
pointer-events: none;
}
.d3-tip.n:after {
content: "\25BC";
margin: -1px 0 0 0;
top: 100%;
left: 0;
text-align: center;
}
</style>
</head>
<body>
</body>
</html>
<script src="/static/js/d3-v4.js"></script>
<script src="/static/js/topojson.js"></script> <!-- 用来处理topojson格式的地图文件 -->
<script src="/static/js/d3-tip.js"></script> <!-- 用来生成tip提示框 -->
<script>
const width = 1200;
const height = 1000;
var svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height"