一.效果图

使用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"

本文展示了如何使用D3.js创建带悬浮提示的渐变色中国地图。关键点包括投影函数的应用、通过node.js(express)服务器提供地图文件、处理 topojson 数据以及前端代码示例。在实现过程中注意不同数据格式的处理,以及解决D3.js版本问题。
最低0.47元/天 解锁文章

被折叠的 条评论
为什么被折叠?



