D3.js制作带悬浮提示框的渐变色中国地图(使用node.js提供服务)

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

一.效果图

在这里插入图片描述

使用D3来制作中国地图主要有几个地方需要注意:

  1. 需要用到投影函数,并挂在在路径生成器上。
  2. 由于同源策略限制的原因,需要通过服务器来返回地图文件,比如china.json这种。
  3. 如果需要做渐变色渲染或者显示标注,需要额外的数据,并通过服务器返回。
  4. 要区分开topojsongeojson两种格式的数据的不同,他们的加载模式也有所不同,相对于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"
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值