vue3 Echarts简单使用与生成地图

553 阅读3分钟

简介

ECharts,一个使用 JavaScript 实现的开源可视化库,可以流畅的运行在 PC 和移动设备上,兼容当前绝大部分浏览器(IE9/10/11,Chrome,Firefox,Safari等),底层依赖矢量图形库 ZRender,提供直观,交互丰富,可高度个性化定制的数据可视化图表。

安装

npm install echarts --save

引入

import * as echarts from 'echarts';

demo

<script lang="ts">
import { onMounted } from 'vue'
import * as echarts from 'echarts';

export default {
  name: 'EchartDemo',
  setup() {
    onMounted(() => {
      // 基于准备好的dom,初始化echarts实例
      var myChart = echarts.init(document.getElementById('echDemo'));
      // 绘制图表
      myChart.setOption({
        title: {
          text: 'ECharts 入门示例'
        },
        tooltip: {},
        xAxis: {
          data: ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子']
        },
        yAxis: {},
        series: [
          {
            name: '销量',
            type: 'bar',
            data: [5, 20, 36, 10, 10, 20]
          }
        ]
      });
    })
    return {  }
  },
}
</script>

<template>
  <div class="echart-demo" id="echDemo"></div>
</template>

<style scoped>
.echart-demo{
  position: relative;
  width: 500px;
  height: 500px;
  padding: 5px;
  border:1px solid #ccc;
}
</style>

应用

//最简单的柱状图
option = {
  xAxis: {
    data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
  },
  yAxis: {},
  series: [
    {
      type: 'bar',
      data: [23, 24, 18, 25, 27, 28, 25]
    }
  ]
};
//堆叠柱状图
option = {
  xAxis: {
    data: ['A', 'B', 'C', 'D', 'E']
  },
  yAxis: {},
  series: [
    {
      data: [10, 22, 28, 43, 49],
      type: 'bar',
      stack: 'x'
    },
    {
      data: [5, 4, 3, 5, 10],
      type: 'bar',
      stack: 'x'
    }
  ]
};
// 更多参考
// https://echarts.apache.org/handbook/zh/how-to/chart-types/bar/stacked-bar

map地图图表

我们首先引入了ECharts库和中国地图的数据。然后初始化了一个图表实例,并设置了基础的配置项。在click事件中处理了地图的三级联动,当点击不同级别的地区时,更新图表的数据。

  // 存储省级区域
  let sheng = null;
  // 存储市区
  let shi = null;
  // 存储区
  let qu = null;
  // 存储点击的是否是县 0=省 1=市 2=区
  let type = 0;

  // 地图配置项
  let option = null;
  // 地图实例
  let myChart = null;
  onMounted(() => {
    // 基于准备好的dom,初始化echarts实例
    myChart = echarts.init(document.getElementById('echMap'));

    nextTick(() => {
      // 处理地图的三级联动
      mapEvent();
    })
    // 初始化中国地图
    initMap();
  })

中国地图 实现

  // 根据geoJson绘制地图
  const initCharts = (zhongguo) => {
    option = {
      // 背景颜色
      backgroundColor: "#00477f",
      // 提示浮窗样式
      tooltip: {
        show: true,
        trigger: "item",
        alwaysShowContent: false,
        backgroundColor: "#0C121C",
        borderColor: "rgba(0, 0, 0, 0.16);",
        hideDelay: 100,
        triggerOn: "mousemove",
        enterable: true,
        textStyle: {
          color: "#DADADA",
          fontSize: "12",
          width: 20,
          height: 30,
          overflow: "break",
        },
        showDelay: 100,
      },
      // 地图配置
      geo: {
        map: "china",
        layoutCenter: ["50%", "50%"], //地图所在的位置
        layoutSize: 600, //地图视图大小
        roam: true, //开启地图缩放和移动
        label: {
          // 通常状态下的样式
          normal: {
            show: true,
            textStyle: {
              color: "#fff",
            },
          },
          // 鼠标放上去的样式
          emphasis: {
            textStyle: {
              color: "#fff",
            },
          },
        },
        // 地图区域的样式设置
        itemStyle: {
          normal: {
            borderColor: "#addef8",
            borderWidth: 1,
            areaColor: {
              type: "radial",
              x: 0.5,
              y: 0.5,
              r: 0.8,
              colorStops: [
                {
                  offset: 0,
                  color: "#61bba1", // 0% 处的颜色
                },
                {
                  offset: 1,
                  color: "#61bba1", // 100% 处的颜色
                },
              ],
              globalCoord: false, // 缺省为 false
            },
            shadowColor: "rgba(128, 217, 248, 1)", //文字块的背景阴影颜色
            shadowOffsetX: -2,
            shadowOffsetY: 2,
            shadowBlur: 10,
          },
          // 鼠标放上去高亮的样式
          emphasis: {
            areaColor: "#addef8",
            borderWidth: 0,
          },
        },
      },
    };

    // 地图注册,第一个参数的名字必须和option.geo.map一致
    echarts.registerMap("china", zhongguo);

    myChart.setOption(option);
  }
  const initMap = () => {
    // 获取中国地图geoJson数据
    axios
      .get("https://geo.datav.aliyun.com/areas_v3/bound/100000_full.json")
      .then((chinaJson) => {
        sheng = chinaJson.data;
        initCharts(chinaJson.data);
      });
  }

三级联动 实现

  const mapEvent = () => {
    // 地图点击事件
    myChart.on("click", (event) => {
      // 是查找省级 还是查找市级
      let code = null;
      if (type == 0) {
        // 市级存在
        code = sheng;
      } else if (type == 1) {
        code = shi;
      } else if (type == 2) {
        code = qu;
      }

      // 查找到上一级的数组坐标
      let num = code.features.findIndex(
        (item) => item.properties.name == event.name
      );

      // 上一级地区的code码
      let adcode = code.features[num].properties.adcode;

      // 点击了文字。传值给后端
      if (event.event.target.culling === false || type == 2) {
        console.log(adcode);
        /*
          这里传值给后端  code = adcode
        */
        return;
      }

      // 获取地图,二三级数据
      axios
        .get(`https://geo.datav.aliyun.com/areas_v3/bound/${adcode}_full.json`)
        .then((chinaJson) => {
          if (type == 0) {
            shi = chinaJson.data;
          } else if (type == 1) {
            qu = chinaJson.data;
          }

          // 缩放
          option.geo.zoom = 0.8;
          // 就像上面提到的,这里必须要和注册地图时的名字一致
          option.geo.map = adcode;
          // 注册地图
          echarts.registerMap(adcode, chinaJson.data);
          // 重新渲染
          myChart.setOption(option, true);

          // 当前地区等级
          type++;
        });
    });

    // 点击空白区域事件
    myChart.getZr().on("click", function (event) {
      // 没有 target 意味着鼠标/指针不在任何一个图形元素上,它是从“空白处”触发的。
      if (!event.target) {
        // 点击在了空白处,做些什么。
        if (type == 0) {
          // 如果在最顶级就返回不做操作
          return;
        }
        // 存值
        let data = null;
        if (type == 2) {
          // 当前是区级
          qu = null;
          data = shi;
          option.geo.zoom = 0.8;
        } else if (type == 1) {
          shi = null;
          data = sheng;
          option.geo.zoom = 1;
        }

        // 就像上面提到的,这里必须要和注册地图时的名字一致
        option.geo.map = "quyu";
        // 注册地图
        echarts.registerMap("quyu", data);
        // 重新渲染
        myChart.setOption(option, true);
        // 当前地区等级
        type--;
      }
    });
  }