Vue使用echarts动态渲染地图,点击某省切换展示成此省的下级市

1 功能介绍

  • 默认展示主地图,点击某个省市区根据地区编码展示对应的省市区地图,当匹配不到对应的省市区编码则展示主地图。
  • 根据地理位置坐标加标记。
    最终效果图

1.1点击省市区展示省市区地图

省市区效果

  • 如果觉得地名位置歪/想让省市区位置在区域中心位置,则需下载地图JSON地图文件进行手动修改(一般名字的位置为省会坐标点),具体修改会在 --- 2.3创建echarts地图 --- 区域写到,因为现在写好像并不清楚到底在写什么。

2 功能实现

2.1 下载所需NPM

npm i axios

npm i echarts

2.2 引入所需配置文件与初始化

2.2.1 编码JSON数据项(由于数据量过大,有需要麻烦移步下面文章获取)

省市区编码JSON数据

2.2.2 初始化

<template>
  <div>
    <div id="echatsMap" style="width: 100%; height: 800px"></div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import axios from "axios";
import { cityCode } from "@/components/cityCode.js";
export default {
  name: "echatsMap",
  components: {},
  data() {
    return {
      cityCode: cityCode,
      myChart: "",
      distributionOptions: "",
    };
  },
  mounted() {},
  methods: {},
};
</script>

2.3 创建echarts地图

  • 此处会用到外部链接来获取地图JSON数据(100000是主视图的地区编码):http://datav.aliyun.com/portal/school/atlas/area_selector#&lat=32.287132632616384&lng=101.1181640625&zoom=4
  • 传递不同的编码,会返回不同省市区的JSON数据。

2.3.1 上面有提到省市区名字可能不在中心位置,可以按以下操作:

  • 点击红框里的下载,就会得到一份本地的JSON文件,2.3.2的代码块为动态获取方式,将本地的JSON地图文件进行修改即可,示例:
      // 此处只举例子
      // 直接在下载的文件里搜甘肃省 --- 这样是默认的
      "properties": {
        "adcode": 620000,
        "name": "甘肃省",
        "center": [
          103.823557,
          36.058039
        ],
        "childrenNum": 14,
        "level": "province",
        "parent": {
          "adcode": 100000
        },
        "subFeatureIndex": 27,
        "acroutes": [
          100000
        ]
      },
      // 在里面加上  用来改变文字展示坐标点
        "cp": [
          103.823557,
          36.058039
        ],
      // 修改后--
      "properties": {
        "adcode": 620000,
        "name": "甘肃省",
        "center": [
          103.823557,
          36.058039
        ],
        "cp": [
          103.823557,
          36.058039
        ],
        "childrenNum": 14,
        "level": "province",
        "parent": {
          "adcode": 100000
        },
        "subFeatureIndex": 27,
        "acroutes": [
          100000
        ]
      },
  • 修改后就不能用动态获取了,需要存放到本地,让其使用本地的文件示例如下(具体改哪来,):
    // 初始化地图数据
    init() {
      // 主地图的JSON文件下载
      let path =  require('../../../../../public/mapJson/china.json');
        echarts.registerMap("china", path );
        this.changeOptions("china");
        this.myChart = echarts.init(document.querySelector("#echatsMap"));
        this.myChart.setOption(this.distributionOptions)
      window.onresize = function () {
        if (this.myChart) this.myChart.resize();
      };
    },

2.3.2 代码实现

<template>
  <div>
    <div id="echatsMap" style="width: 100%; height: 800px"></div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import axios from "axios";
import { cityCode } from "@/components/cityCode.js";
export default {
  name: "echatsMap",
  components: {},
  data() {
    return {
      cityCode: cityCode,
      myChart: "",
      distributionOptions: "",
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.init();
    });
  },
  methods: {
    // 初始化地图数据
    init() {
      // 主地图的JSON文件下载
      let path = `https://geo.datav.aliyun.com/areas_v3/bound/100000_full.json`;
      axios.get(path).then((res) => {
        echarts.registerMap("china", res.data);
        this.changeOptions("china");
        this.myChart = echarts.init(document.querySelector("#echatsMap"));
        this.myChart.setOption(this.distributionOptions)
      });
      window.onresize = function () {
        if (this.myChart) this.myChart.resize();
      };
    },
    // echarts 配置项
    changeOptions(name) {
      // 经纬度数据
      const seriesList = [
        {
          data: [{ value: [106.9, 27.7] }, { value: [105.29, 27.32] }],
        },
      ];
      // 图标
      const series = seriesList.map((v) => {
        return {
          type: "scatter", //配置显示方式为用户自定义
          coordinateSystem: "geo",
          data: v.data,
          // 自定义图标的样式  支持svg与bse64
          symbol: function (params, key) {
            return "image://" + require("@/assets/logo.png");
          },
          symbolSize: 16,
        };
      });

      // options
      this.distributionOptions = {
        tooltip: {
          // 提示框组件
          show: true, // 显示提示框组件
          trigger: "item", // 触发类型
          triggerOn: "mousemove", // 触发条件
          formatter: "名称:{b}<br/>坐标:{c}",
        },
        series, // 数据
        geo: {
          map: name || "china", // 引入地图 省份或者 国家
          layoutCenter: ["50%", "50%"], //设置后left/right/top/bottom等属性无效
          layoutSize: "45%",
          roam: true, //开启鼠标缩放
          zoom: 2,
          label: {
            normal: {
              //静态的时候展示样式
              show: true, //是否显示地图省份得名称
              textStyle: {
                color: "#fff",
                fontSize: 10,
                fontFamily: "Arial",
              },
            },
            emphasis: {
              // 高亮状态下的样式
              //动态展示的样式
              color: "#fff",
            },
          },
          itemStyle: {
            // 地图区域的多边形 图形样式。
            normal: {
              borderColor: "#fff", // 边框颜色
              areaColor: "#1c2f59", //  区域颜色
              // areaColor: { // 使用背景图片
              //   type: "pattern",
              //   image: require("@/assets/texture.jpeg"), // 使用自己本地图片路径
              //   repeat: "repeat", //可选值repeat、no-repeat、repeat-x、repeat-y
              // },
              textStyle: {
                // 文字颜色
                color: "#fff",
              },
              // shadowBlur: 10, // 图形阴影的模糊大小
              // shadowOffsetX: 10, // 阴影水平方向上的偏移距离。
            },
            emphasis: {
              areaColor: "#1c2f59",
              color: "#fff",
            },
          },
          regions: [
            //对不同的区块进行着色
            // {
            //   name: "河南省", //区块名称
            //   itemStyle: {
            //     normal: {
            //       areaColor: "#281fe1",
            //     },
            //   },
            // },
            // {
            //   name: "浙江省", //区块名称
            //   itemStyle: {
            //     normal: {
            //       areaColor: "#193094",
            //     },
            //   },
            // },
          ],
        },
      };
    },
  },
};
</script>

2.4 点击地图省市区展示省市区地图

  • 大概就是点击省市区时根据名称与编码文件去匹配,把匹配到的编码通过外部接口去获取想要的省市区JSON地图数据。再次渲染echarts即可。
  • 注意:如果没匹配到需跳主地图/获取不到此区域的JSON地图数据。
<template>
  <div>
    <div id="echatsMap" style="width: 100%; height: 800px"></div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import axios from "axios";
import { cityCode } from "@/components/cityCode.js";
export default {
  name: "echatsMap",
  components: {},
  data() {
    return {
      cityCode: cityCode,
      myChart: "",
      distributionOptions: "",
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.init();
    });
  },
  methods: {
    // 初始化地图数据
    init() {
      // 主地图的JSON文件下载
      let path = `https://geo.datav.aliyun.com/areas_v3/bound/100000_full.json`;
      axios.get(path).then((res) => {
        echarts.registerMap("china", res.data);
        this.changeOptions("china");
        this.myChart = echarts.init(document.querySelector("#echatsMap"));
        this.myChart.setOption(this.distributionOptions);
        // 点击省份子区域的时候可以切换到省份地图
        this.myChart.on("click", (chinaParam) => {
          // 如果没有下层则展示主地图
          if (!this.cityCode) {
            this.cityCode = cityCode;
            // 100000 主地图
            this.getProvinceMapOpt(100000, "")
            return;
          }
          // 根据点击位置地图名字去跟编码数据匹配
          let code = this.cityCode.find(
            (x) => chinaParam.name.indexOf(x ? x.name : "") !== -1
          );
          // 找到正确的编码   去获取对应的地图数据
          // 将该省市区的下级放入 -- 如果接口支持根据编码查询省市区所有下级子级就不需要这么写
          if (code) {
            this.cityCode = code.city;
            this.getProvinceMapOpt(Number(code.adcode), chinaParam.name);
          } else {
            // 没有对应的编码跳主地图
            this.cityCode = cityCode;
            // 100000 主地图
            this.getProvinceMapOpt(100000, "");
          }
        });
      });
      window.onresize = function () {
        if (this.myChart) this.myChart.resize();
      };
    },
    // 下载/显示各省地图
    getProvinceMapOpt(provinceAlphabet, name) {
      // 根据地区编码获取所在地区的JSON地图
      let path = `https://geo.datav.aliyun.com/areas_v3/bound/${provinceAlphabet}_full.json`;
      if (provinceAlphabet === 100000) {
        path = "/mapJson/china.json";
      }
      axios.get(path).then((res) => {
        // 获取完最新的JSON地图数据后,重新渲染
        echarts.registerMap(name, res.data);
        this.changeOptions(name);
        this.myChart.setOption(this.distributionOptions, true);
      });
    },
    // echarts 配置项
    changeOptions(name) {
      // 经纬度数据  --- 不存在的经纬度不会展示出来
      const seriesList = [
        {
          data: [{ value: [106.9, 27.7] }, { value: [105.29, 27.32] }],
        },
      ];
      // 图标
      const series = seriesList.map((v) => {
        return {
          type: "scatter", //配置显示方式为用户自定义
          coordinateSystem: "geo",
          data: v.data,
          // 自定义图标的样式  支持svg与bse64
          symbol: function (params, key) {
            return "image://" + require("@/assets/logo.png");
          },
          symbolSize: 16,
        };
      });

      // options
      this.distributionOptions = {
        tooltip: {
          // 提示框组件
          show: true, // 显示提示框组件
          trigger: "item", // 触发类型
          triggerOn: "mousemove", // 触发条件
          formatter: "名称:{b}<br/>坐标:{c}",
        },
        series, // 数据
        geo: {
          map: name || "china", // 引入地图 省份或者 国家
          layoutCenter: ["50%", "50%"], //设置后left/right/top/bottom等属性无效
          layoutSize: "45%",
          roam: true, //开启鼠标缩放
          zoom: 2,
          label: {
            normal: {
              //静态的时候展示样式
              show: true, //是否显示地图省份得名称
              textStyle: {
                color: "#fff",
                fontSize: 10,
                fontFamily: "Arial",
              },
            },
            emphasis: {
              // 高亮状态下的样式
              //动态展示的样式
              color: "#fff",
            },
          },
          itemStyle: {
            // 地图区域的多边形 图形样式。
            normal: {
              borderColor: "#fff", // 边框颜色
              areaColor: "#1c2f59", //  区域颜色
              textStyle: {
                // 文字颜色
                color: "#fff",
              },
              // shadowBlur: 10, // 图形阴影的模糊大小
              // shadowOffsetX: 10, // 阴影水平方向上的偏移距离。
            },
            emphasis: {
              areaColor: "#1c2f59",
              color: "#fff",
            },
          },
          regions: [
            //对不同的区块进行着色
            // {
            //   name: "河南省", //区块名称
            //   itemStyle: {
            //     normal: {
            //       areaColor: "#281fe1",
            //     },
            //   },
            // },
            // {
            //   name: "浙江省", //区块名称
            //   itemStyle: {
            //     normal: {
            //       areaColor: "#193094",
            //     },
            //   },
            // },
          ],
        },
      };
    },
  },
};
</script>

3 china版地图完整代码

<template>
  <div>
    <div id="echatsMap" style="width: 100%; height: 800px"></div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import axios from "axios";
import { cityCode } from "@/components/cityCode.js";
export default {
  name: "echatsMap",
  components: {},
  data() {
    return {
      cityCode: cityCode,
      myChart: "",
      distributionOptions: "",
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.init();
    });
  },
  methods: {
    // 初始化地图数据
    init() {
      // 主地图的JSON文件下载
      let path = `https://geo.datav.aliyun.com/areas_v3/bound/100000_full.json`;
      axios.get(path).then((res) => {
        echarts.registerMap("china", res.data);
        this.changeOptions("china");
        this.myChart = echarts.init(document.querySelector("#echatsMap"));
        this.myChart.setOption(this.distributionOptions);
        // 点击省份子区域的时候可以切换到省份地图
        this.myChart.on("click", (chinaParam) => {
          // 如果没有下层则展示主地图
          if (!this.cityCode) {
            this.cityCode = cityCode;
            // 100000 主地图
            this.getProvinceMapOpt(100000, "")
            return;
          }
          // 根据点击位置地图名字去跟编码数据匹配
          let code = this.cityCode.find(
            (x) => chinaParam.name.indexOf(x ? x.name : "") !== -1
          );
          // 找到正确的编码   去获取对应的地图数据
          // 将该省市区的下级放入 -- 如果接口支持根据编码查询省市区所有下级子级就不需要这么写
          if (code) {
            this.cityCode = code.city;
            this.getProvinceMapOpt(Number(code.adcode), chinaParam.name);
          } else {
            // 没有对应的编码跳主地图
            this.cityCode = cityCode;
            // 100000 主地图
            this.getProvinceMapOpt(100000, "");
          }
        });
      });
      window.onresize = function () {
        if (this.myChart) this.myChart.resize();
      };
    },
    // 下载/显示各省地图
    getProvinceMapOpt(provinceAlphabet, name) {
      // 根据地区编码获取所在地区的JSON地图
      let path = `https://geo.datav.aliyun.com/areas_v3/bound/${provinceAlphabet}_full.json`;
      if (provinceAlphabet === 100000) {
        path = "/mapJson/china.json";
      }
      axios.get(path).then((res) => {
        // 获取完最新的JSON地图数据后,重新渲染
        echarts.registerMap(name, res.data);
        this.changeOptions(name);
        this.myChart.setOption(this.distributionOptions, true);
      });
    },
    // echarts 配置项
    changeOptions(name) {
      // 经纬度数据  --- 不存在的经纬度不会展示出来
      const seriesList = [
        {
          data: [{ value: [106.9, 27.7] }, { value: [105.29, 27.32] }],
        },
      ];
      // 图标
      const series = seriesList.map((v) => {
        return {
          type: "scatter", //配置显示方式为用户自定义
          coordinateSystem: "geo",
          data: v.data,
          // 自定义图标的样式  支持svg与bse64
          symbol: function (params, key) {
            return "image://" + require("@/assets/logo.png");
          },
          symbolSize: 16,
        };
      });

      // options
      this.distributionOptions = {
        tooltip: {
          // 提示框组件
          show: true, // 显示提示框组件
          trigger: "item", // 触发类型
          triggerOn: "mousemove", // 触发条件
          formatter: "名称:{b}<br/>坐标:{c}",
        },
        series, // 数据
        geo: {
          map: name || "china", // 引入地图 省份或者 国家
          layoutCenter: ["50%", "50%"], //设置后left/right/top/bottom等属性无效
          layoutSize: "45%",
          roam: true, //开启鼠标缩放
          zoom: 2,
          label: {
            normal: {
              //静态的时候展示样式
              show: true, //是否显示地图省份得名称
              textStyle: {
                color: "#fff",
                fontSize: 10,
                fontFamily: "Arial",
              },
            },
            emphasis: {
              // 高亮状态下的样式
              //动态展示的样式
              color: "#fff",
            },
          },
          itemStyle: {
            // 地图区域的多边形 图形样式。
            normal: {
              borderColor: "#fff", // 边框颜色
              areaColor: "#1c2f59", //  区域颜色
              textStyle: {
                // 文字颜色
                color: "#fff",
              },
              // shadowBlur: 10, // 图形阴影的模糊大小
              // shadowOffsetX: 10, // 阴影水平方向上的偏移距离。
            },
            emphasis: {
              areaColor: "#1c2f59",
              color: "#fff",
            },
          },
          regions: [
            //对不同的区块进行着色
            // {
            //   name: "河南省", //区块名称
            //   itemStyle: {
            //     normal: {
            //       areaColor: "#281fe1",
            //     },
            //   },
            // },
            // {
            //   name: "浙江省", //区块名称
            //   itemStyle: {
            //     normal: {
            //       areaColor: "#193094",
            //     },
            //   },
            // },
          ],
        },
      };
    },
  },
};
</script>

4 展示某个省的地图

4.1 展示某个省的地图的话,要做一些修改

  • 修改默认请求的Json数据
  • 修改默认展示的地图名字等
    在这里插入图片描述

4.2 效果图

效果图

4.3 完整代码

4.3.1 地区编码文件

// utils/cityCode.js
// cityCode.js

export const cityCode = [{
  "adcode": "420100",
  "name": "武汉"
}, {
  "adcode": "420200",
  "name": "黄石"
}, {
  "adcode": "420300",
  "name": "十堰"
}, {
  "adcode": "420500",
  "name": "宜昌"
}, {
  "adcode": "420600",
  "name": "襄阳"
}, {
  "adcode": "420700",
  "name": "鄂州"
}, {
  "adcode": "420800",
  "name": "荆门"
}, {
  "adcode": "420900",
  "name": "孝感"
}, {
  "adcode": "421000",
  "name": "荆州"
}, {
  "adcode": "421100",
  "name": "黄冈"
}, {
  "adcode": "421200",
  "name": "咸宁"
}, {
  "adcode": "421300",
  "name": "随州"
}, {
  "adcode": "422800",
  "name": "恩施土家族苗族自治州"
}, {
  "adcode": "429004",
  "name": "仙桃"
}, {
  "adcode": "429005",
  "name": "潜江"
}, {
  "adcode": "429006",
  "name": "天门"
}, {
  "adcode": "429021",
  "name": "神农架林区"
}
]


4.3.2 视图文件

<template>
  <div>
    <div id="echatsMap" style="width: 100%; height: 800px"></div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import axios from "axios";
import { cityCode } from "@/utils/cityCode.js";
export default {
  name: "echatsMap",
  components: {},
  data () {
    return {
      cityCode: cityCode,
      myChart: "",
      distributionOptions: "",
      geographicalCoordinates: [{ name: '荆州市', value: [112.239741, 30.335165] }]
    };
  },
  mounted () {
    this.$nextTick(() => {
      this.init();
    });
  },
  methods: {
    // 初始化地图数据
    init () {
      // 主地图的JSON文件下载
      let path = `https://geo.datav.aliyun.com/areas_v3/bound/420000_full.json`;
      axios.get(path).then((res) => {
        echarts.registerMap("湖北省", res.data);
        this.changeOptions("湖北省");
        this.myChart = echarts.init(document.querySelector("#echatsMap"));
        this.myChart.setOption(this.distributionOptions);
        // 点击省份子区域的时候可以切换到省份地图
        this.myChart.on("click", (chinaParam) => {
          // 如果没有下层则展示主地图
          if (!this.cityCode) {
            this.cityCode = cityCode;
            // 420000 主地图
            this.geographicalCoordinates = [{ name: '荆州市', value: [112.239741, 30.335165] }]
            this.getProvinceMapOpt(420000, "")
            return;
          }
          // 根据点击位置地图名字去跟编码数据匹配
          let code = this.cityCode.find(
            (x) => chinaParam.name.indexOf(x ? x.name : "") !== -1
          );
          // 找到正确的编码   去获取对应的地图数据
          // 将该省市区的下级放入 -- 如果接口支持根据编码查询省市区所有下级子级就不需要这么写
          if (code) {
            this.cityCode = code.city;
            this.geographicalCoordinates = []
            this.getProvinceMapOpt(Number(code.adcode), chinaParam.name);
          } else {
            // 没有对应的编码跳主地图
            this.cityCode = cityCode;
            // 420000 主地图
            this.geographicalCoordinates = [{ name: '荆州市', value: [112.239741, 30.335165] }]
            this.getProvinceMapOpt(420000, "湖北省");
          }
        });
      });
      window.onresize = function () {
        if (this.myChart) this.myChart.resize();
      };
    },
    // 下载/显示各省地图
    getProvinceMapOpt (provinceAlphabet, name) {
      // 根据地区编码获取所在地区的JSON地图
      let path = `https://geo.datav.aliyun.com/areas_v3/bound/${provinceAlphabet}_full.json`;
      // if (provinceAlphabet === 420000) {
      //   path = "/mapJson/china.json";
      // }
      axios.get(path).then((res) => {
        // 获取完最新的JSON地图数据后,重新渲染
        echarts.registerMap(name, res.data);
        this.changeOptions(name);
        this.myChart.setOption(this.distributionOptions, true);
      });
    },
    // echarts 配置项
    changeOptions (name) {
      // 经纬度数据  --- 不存在的经纬度不会展示出来
      const seriesList = [
        {
          data: this.geographicalCoordinates,
        },
      ];
      // 图标
      const series = seriesList.map((v) => {
        return {
          type: "scatter", //配置显示方式为用户自定义
          coordinateSystem: "geo",
          data: v.data,
          // 自定义图标的样式  支持svg与bse64
          symbol: function (params, key) {
            return "image://" + require("@/assets/logo.png");
          },
          symbolSize: 16,
          tooltip: {
            trigger: 'item',
            // show:false,
            formatter: function (params) {
              // 自定义 tooltip 内容
              return `名称:${params.data.name}<br/>坐标:<br/>经度:${params.data.value[0]}<br/>纬度:${params.data.value[1]}`;
            },
          },
        };
      });

      // options
      this.distributionOptions = {
        tooltip: {},
        series, // 数据
        geo: {
          map: name || "湖北省", // 引入地图 省份或者 国家
          layoutCenter: ["50%", "50%"], //设置后left/right/top/bottom等属性无效
          layoutSize: "55%",
          roam: true, //开启鼠标缩放
          zoom: 2,
          label: {
            normal: {
              //静态的时候展示样式
              show: true, //是否显示地图省份得名称
              textStyle: {
                color: "#000",
                fontSize: 10,
                fontFamily: "Arial",
              },
            },
            emphasis: {
              // 高亮状态下的样式
              //动态展示的样式
              color: "#fff",
            },
          },
          itemStyle: {
            normal: {
              borderColor: 'rgba(147, 235, 248, 1)',
              borderWidth: 1,
              areaColor: {
                type: 'radial',
                x: 0.5,
                y: 0.5,
                r: 0.8,
                colorStops: [{
                  offset: 0,
                  color: 'rgba(147, 235, 248, 0)' // 0% 处的颜色
                }, {
                  offset: 1,
                  color: 'rgba(147, 235, 248, .2)' // 100% 处的颜色
                }],
                globalCoord: false // 缺省为 false
              },
              shadowColor: 'rgba(128, 217, 248, 1)',
              // shadowColor: 'rgba(255, 255, 255, 1)',
              shadowOffsetX: -2,
              shadowOffsetY: 2,
              shadowBlur: 10
            },
            emphasis: {
              areaColor: '#389BB7',
              borderWidth: 0
            }
          },
          regions: [
            //对不同的区块进行着色
            // {
            //   name: "河南省", //区块名称
            //   itemStyle: {
            //     normal: {
            //       areaColor: "#281fe1",
            //     },
            //   },
            // },
            // {
            //   name: "浙江省", //区块名称
            //   itemStyle: {
            //     normal: {
            //       areaColor: "#193094",
            //     },
            //   },
            // },
          ],
        },
      };
    },
  },
};
</script>


4 展示到县级别

  • 县级别以上都是用的 https://geo.datav.aliyun.com/areas_v3/bound/${区域编码}_full.json去获取的JSON地图数据,但到了县这个请求地址就变了,变成了https://geo.datav.aliyun.com/areas_v3/bound/${区域编码}.json
  • 以下将以 4 展示某个省的地图完整代码进行修改

4.1 添加县级以上请求地图数据失败捕获

4.1.1 添加错误捕获

    // 下载/显示各省地图
    getProvinceMapOpt (provinceAlphabet, name) {
      // console.log(provinceAlphabet);
      // 根据地区编码获取所在地区的JSON地图
      let path = `https://geo.datav.aliyun.com/areas_v3/bound/${provinceAlphabet}_full.json`;
      // if (provinceAlphabet === 420000) {
      //   path = "/mapJson/china.json";
      // }
      axios.get(path).then((res) => {

        // 获取完最新的JSON地图数据后,重新渲染
        echarts.registerMap(name, res.data);
        this.changeOptions(name);
        this.myChart.setOption(this.distributionOptions, true);
      }).catch((error) => {
        // 请求出错时的处理逻辑 - 此时有可能是请求到县了,县的请求地址跟其他层级请求地址不一样
        console.error('请求出错:', error);
      });
    },

4.1.2 添加请求县级的JSON地图数据方法

	// 获取县级别的地图数据
        getProvinceMapOptCounty (provinceAlphabet, name) {
      // 根据地区编码获取所在地区的JSON地图
      let path = `https://geo.datav.aliyun.com/areas_v3/bound/${provinceAlphabet}.json`;
      axios.get(path).then((res) => {

        // 获取完最新的JSON地图数据后,重新渲染
        echarts.registerMap(name, res.data);
        this.changeOptions(name);
        this.myChart.setOption(this.distributionOptions, true);
      }).catch((error) => {
        // 请求出错时的处理逻辑 - 此时有可能是请求到县了,县的请求地址跟其他层级请求地址不一样
        console.error('请求出错:', error);
      });
    },
  • 此时在县级别以上获取数据失败时去请求,并记录此时请求到了县级别(因为没有县级以下的数据了,再点击县的话就返回第一级)
  • 需要再点击县的话就返回第一级代码
data () {
     return {
       geoCounty: false,
   	 }
}
    // 初始化地图数据
    init () {
      // 主地图的JSON文件下载
      let path = `https://geo.datav.aliyun.com/areas_v3/bound/420000_full.json`;
      axios.get(path).then((res) => {
        echarts.registerMap("湖北省", res.data);
        this.changeOptions("湖北省");
        this.myChart = echarts.init(document.querySelector("#echatsMap"));
        this.myChart.setOption(this.distributionOptions);
        // 点击省份子区域的时候可以切换到省份地图
        this.myChart.on("click", (chinaParam) => {
          // 如果没有下层则展示主地图
          if (!this.cityCode) {
            this.cityCode = cityCode;
            // 420000 主地图
            this.geoCounty = false
            this.getProvinceMapOpt(420000, "")
            return;
          }
          // 根据点击位置地图名字去跟编码数据匹配
          let code = this.cityCode.find(
            (x) => chinaParam.name.indexOf(x ? x.name : "") !== -1
          );
          // console.log(chinaParam.name,'---',code);
          // 找到正确的编码   去获取对应的地图数据
          // 将该省市区的下级放入 -- 如果接口支持根据编码查询省市区所有下级子级就不需要这么写
          if (code) {
            // 判断是否请求到了县级别
            if (!this.geoCounty) {
              this.getProvinceMapOpt(Number(code.adcode), chinaParam.name);
            } else {
              // this.getProvinceMapOptCounty(Number(code.adcode), chinaParam.name);
              // 已经没有再下层的数据了,再点击返回主视图
              this.cityCode = cityCode;
              // 420000 主地图
              this.geoCounty = false
              this.getProvinceMapOpt(420000, "湖北省");
            }
          } else {
            // 没有对应的编码跳主地图
            this.cityCode = cityCode;
            // 420000 主地图
            this.geoCounty = false
            this.getProvinceMapOpt(420000, "湖北省");
          }
        });
      });
      window.onresize = function () {
        if (this.myChart) this.myChart.resize();
      };
    },
// 下载/显示各省地图
    getProvinceMapOpt (provinceAlphabet, name) {
      console.log(provinceAlphabet);
      // 根据地区编码获取所在地区的JSON地图
      let path = `https://geo.datav.aliyun.com/areas_v3/bound/${provinceAlphabet}_full.json`;
      // if (provinceAlphabet === 420000) {
      //   path = "/mapJson/china.json";
      // }
      axios.get(path).then((res) => {

        // 获取完最新的JSON地图数据后,重新渲染
        echarts.registerMap(name, res.data);
        this.changeOptions(name);
        this.myChart.setOption(this.distributionOptions, true);
      }).catch((error) => {
        this.geoCounty = true
        // 请求出错时的处理逻辑 - 此时有可能是请求到县了,县的请求地址跟其他层级请求地址不一样
        this.getProvinceMapOptCounty(provinceAlphabet, name)
        // console.error('请求出错:', error);
      });
    },
    // 获取县级别的地图数据
    getProvinceMapOptCounty (provinceAlphabet, name) {
      // 根据地区编码获取所在地区的JSON地图
      let path = `https://geo.datav.aliyun.com/areas_v3/bound/${provinceAlphabet}.json`;
      axios.get(path).then((res) => {

        // 获取完最新的JSON地图数据后,重新渲染
        echarts.registerMap(name, res.data);
        this.changeOptions(name);
        this.myChart.setOption(this.distributionOptions, true);
      }).catch((error) => {
        // 请求出错时的处理逻辑 - 此时有可能是请求到县了,县的请求地址跟其他层级请求地址不一样
        console.error('请求出错:', error);
      });
    },
  • 不需要再点击县的话就返回第一级
// 下载/显示各省地图
    getProvinceMapOpt (provinceAlphabet, name) {
      // 根据地区编码获取所在地区的JSON地图
      let path = `https://geo.datav.aliyun.com/areas_v3/bound/${provinceAlphabet}_full.json`;
      // if (provinceAlphabet === 420000) {
      //   path = "/mapJson/china.json";
      // }
      axios.get(path).then((res) => {

        // 获取完最新的JSON地图数据后,重新渲染
        echarts.registerMap(name, res.data);
        this.changeOptions(name);
        this.myChart.setOption(this.distributionOptions, true);
      }).catch((error) => {
        this.geoCounty = true
        // 请求出错时的处理逻辑 - 此时有可能是请求到县了,县的请求地址跟其他层级请求地址不一样
        this.getProvinceMapOptCounty(provinceAlphabet, name)
        // console.error('请求出错:', error);
      });
    },
    // 获取县级别的地图数据
    getProvinceMapOptCounty (provinceAlphabet, name) {
      // 根据地区编码获取所在地区的JSON地图
      let path = `https://geo.datav.aliyun.com/areas_v3/bound/${provinceAlphabet}.json`;
      axios.get(path).then((res) => {

        // 获取完最新的JSON地图数据后,重新渲染
        echarts.registerMap(name, res.data);
        this.changeOptions(name);
        this.myChart.setOption(this.distributionOptions, true);
      }).catch((error) => {
        // 请求出错时的处理逻辑 - 此时有可能是请求到县了,县的请求地址跟其他层级请求地址不一样
        console.error('请求出错:', error);
      });
    },

4.2 修改地区编码(cityCode.js)文件

// cityCode.js

export const cityCode = [{
  "adcode": "420100",
  "name": "武汉"
}, {
  "adcode": "420200",
  "name": "黄石市"
}, {
  "adcode": "420300",
  "name": "十堰"
}, {
  "adcode": "420500",
  "name": "宜昌市"
}, {
  "adcode": "420600",
  "name": "襄阳"
}, {
  "adcode": "420700",
  "name": "鄂州"
}, {
  "adcode": "420800",
  "name": "荆门"
}, {
  "adcode": "420900",
  "name": "孝感"
}, {
  "adcode": "421000",
  "name": "荆州市"
}, {
  "adcode": "421100",
  "name": "黄冈"
}, {
  "adcode": "421200",
  "name": "咸宁"
}, {
  "adcode": "421300",
  "name": "随州"
}, {
  "adcode": "422800",
  "name": "恩施土家族苗族自治州"
}, {
  "adcode": "429004",
  "name": "仙桃"
}, {
  "adcode": "429005",
  "name": "潜江"
}, {
  "adcode": "429006",
  "name": "天门"
}, {
  "adcode": "429021",
  "name": "神农架林区"
}, {
  "adcode": "420322",
  "name": "郧西县"
}, {
  "adcode": "420304",
  "name": "郧阳区"
}, {
  "adcode": "420381",
  "name": "丹江口市"
}, {
  "adcode": "420303",
  "name": "张湾区"
}, {
  "adcode": "420302",
  "name": "茅箭区"
}, {
  "adcode": "420323",
  "name": "竹山县"
}, {
  "adcode": "420325",
  "name": "房县"
}, {
  "adcode": "420324",
  "name": "竹溪县"
}, {
  "adcode": "420682",
  "name": "老河口市"
}, {
  "adcode": "420607",
  "name": "襄州区"
}, {
  "adcode": "420683",
  "name": "枣阳市"
}, {
  "adcode": "420625",
  "name": "谷城县"
}, {
  "adcode": "420606",
  "name": "樊城区"
}, {
  "adcode": "420602",
  "name": "襄城区"
}, {
  "adcode": "420684",
  "name": "宜城市"
}, {
  "adcode": "420626",
  "name": "保康县"
}, {
  "adcode": "420624",
  "name": "南漳县"
}, {
  "adcode": "421321",
  "name": "随县"
}, {
  "adcode": "421303",
  "name": "曾都区"
}, {
  "adcode": "421381",
  "name": "广水市"
}, {
  "adcode": "420922",
  "name": "大悟县"
}, {
  "adcode": "420982",
  "name": "安陆市"
}, {
  "adcode": "420921",
  "name": "孝昌县"
}, {
  "adcode": "420981",
  "name": "应城市"
}, {
  "adcode": "420923",
  "name": "云梦县"
}, {
  "adcode": "420902",
  "name": "孝南区"
}, {
  "adcode": "420984",
  "name": "汉川市"
}, {
  "adcode": "421122",
  "name": "红安县"
}, {
  "adcode": "421181",
  "name": "麻城市"
}, {
  "adcode": "421123",
  "name": "罗田县"
}, {
  "adcode": "421124",
  "name": "英山县"
}, {
  "adcode": "421121",
  "name": "团风县"
}, {
  "adcode": "421125",
  "name": "浠水县"
}, {
  "adcode": "421126",
  "name": "蕲春县"
}, {
  "adcode": "421182",
  "name": "武穴市"
}, {
  "adcode": "421127",
  "name": "黄梅县"
}, {
  "adcode": "421102",
  "name": "黄州区"
}, {
  "adcode": "420281",
  "name": "大冶市"
}, {
  "adcode": "420205",
  "name": "铁山区"
}, {
  "adcode": "420204",
  "name": "下陆区"
}, {
  "adcode": "420202",
  "name": "黄石港区"
}, {
  "adcode": "420203",
  "name": "西塞山区"
}, {
  "adcode": "420222",
  "name": "阳新县"
}, {
  "adcode": "420703",
  "name": "华容区"
}, {
  "adcode": "420704",
  "name": "鄂城区"
}, {
  "adcode": "420702",
  "name": "梁子湖区"
}, {
  "adcode": "420116",
  "name": "黄陂区"
}, {
  "adcode": "420117",
  "name": "新洲区"
}, {
  "adcode": "420112",
  "name": "东西湖区"
}, {
  "adcode": "420102",
  "name": "江岸区"
}, {
  "adcode": "420103",
  "name": "江汉区"
}, {
  "adcode": "420104",
  "name": "硚口区"
}, {
  "adcode": "420107",
  "name": "青山区"
}, {
  "adcode": "420106",
  "name": "武昌区"
}, {
  "adcode": "420111",
  "name": "洪山区"
}, {
  "adcode": "420105",
  "name": "汉阳区"
}, {
  "adcode": "420114",
  "name": "蔡甸区"
}, {
  "adcode": "420113",
  "name": "汉南区"
}, {
  "adcode": "420115",
  "name": "江夏区"
}, {
  "adcode": "420802",
  "name": "东宝区"
}, {
  "adcode": "420881",
  "name": "钟祥市"
}, {
  "adcode": "420882",
  "name": "京山市"
}, {
  "adcode": "420804",
  "name": "掇刀区"
}, {
  "adcode": "420822",
  "name": "沙洋县"
}, {
  "adcode": "422802",
  "name": "利川市"
}, {
  "adcode": "422801",
  "name": "恩施市"
}, {
  "adcode": "422822",
  "name": "建始县"
}, {
  "adcode": "422823",
  "name": "巴东县"
}, {
  "adcode": "422828",
  "name": "鹤峰县"
}, {
  "adcode": "422825",
  "name": "宣恩县"
}, {
  "adcode": "422826",
  "name": "咸丰县"
}, {
  "adcode": "422827",
  "name": "来凤县"
}, {
  "adcode": "420526",
  "name": "兴山县"
}, {
  "adcode": "420506",
  "name": "夷陵区"
}, {
  "adcode": "420525",
  "name": "远安县"
}, {
  "adcode": "420582",
  "name": "当阳市"
}, {
  "adcode": "420583",
  "name": "枝江市"
}, {
  "adcode": "420505",
  "name": "猇亭区"
}, {
  "adcode": "420503",
  "name": "伍家岗区"
}, {
  "adcode": "420502",
  "name": "西陵区"
}, {
  "adcode": "420504",
  "name": "点军区"
}, {
  "adcode": "420527",
  "name": "秭归县"
}, {
  "adcode": "420528",
  "name": "长阳土家族自治县"
}, {
  "adcode": "420529",
  "name": "五峰土家族自治县"
}, {
  "adcode": "420581",
  "name": "宜都市"
}, {
  "adcode": "421087",
  "name": "松滋市"
}, {
  "adcode": "421003",
  "name": "荆州区"
}, {
  "adcode": "421022",
  "name": "公安县"
}, {
  "adcode": "421002",
  "name": "沙市区"
}, {
  "adcode": "421024",
  "name": "江陵县"
}, {
  "adcode": "421081",
  "name": "石首市"
}, {
  "adcode": "421023",
  "name": "监利市"
}, {
  "adcode": "421023",
  "name": "监利市"
}, {
  "adcode": "421083",
  "name": "洪湖市"
},{
  "adcode": "421221",
  "name": "嘉鱼县"
},{
  "adcode": "421202",
  "name": "咸安区"
},{
  "adcode": "421224",
  "name": "通山县"
},{
  "adcode": "421281",
  "name": "赤壁市"
},{
  "adcode": "421223",
  "name": "崇阳县"
},{
  "adcode": "421222",
  "name": "通城县"
},
]

4.3 完整代码(默认带再点击县的话就返回第一级)

<template>
  <div>
    <div id="echatsMap" style="width: 100%; height: 800px"></div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import axios from "axios";
import { cityCode } from "@/utils/cityCode.js";
export default {
  name: "echatsMap",
  components: {},
  data () {
    return {
      cityCode: cityCode,
      myChart: "",
      distributionOptions: "",
      geographicalCoordinates: [
        { name: '荆州市', adcode: '421000', value: [112.239741, 30.335165], chiidren: [{ name: '公安县', adcode: '420325', value: [112.230407, 30.058336] }] },
      ],
      geoCounty: false,
    };
  },
  mounted () {
    this.$nextTick(() => {
      this.init();
    });
  },
  methods: {
    // 初始化地图数据
    init () {
      // 主地图的JSON文件下载
      let path = `https://geo.datav.aliyun.com/areas_v3/bound/420000_full.json`;
      axios.get(path).then((res) => {
        echarts.registerMap("湖北省", res.data);
        this.changeOptions("湖北省");
        this.myChart = echarts.init(document.querySelector("#echatsMap"));
        this.myChart.setOption(this.distributionOptions);
        // 点击省份子区域的时候可以切换到省份地图
        this.myChart.on("click", (chinaParam) => {
          // 如果没有下层则展示主地图
          if (!this.cityCode) {
            this.cityCode = cityCode;
            // 420000 主地图
            this.geoCounty = false
            this.getProvinceMapOpt(420000, "")
            return;
          }
          // 根据点击位置地图名字去跟编码数据匹配
          let code = this.cityCode.find(
            (x) => chinaParam.name.indexOf(x ? x.name : "") !== -1
          );
          // console.log(chinaParam.name,'---',code);
          // 找到正确的编码   去获取对应的地图数据
          // 将该省市区的下级放入 -- 如果接口支持根据编码查询省市区所有下级子级就不需要这么写
          if (code) {
            // 判断是否请求到了县级别
            if (!this.geoCounty) {
              this.getProvinceMapOpt(Number(code.adcode), chinaParam.name);
            } else {
              // this.getProvinceMapOptCounty(Number(code.adcode), chinaParam.name);
              // 已经没有再下层的数据了,再点击返回主视图
              this.cityCode = cityCode;
              // 420000 主地图
              this.geoCounty = false
              this.getProvinceMapOpt(420000, "湖北省");
            }
          } else {
            // 没有对应的编码跳主地图
            this.cityCode = cityCode;
            // 420000 主地图
            this.geoCounty = false
            this.getProvinceMapOpt(420000, "湖北省");
          }
        });
      });
      window.onresize = function () {
        if (this.myChart) this.myChart.resize();
      };
    },
    // 下载/显示各省地图
    getProvinceMapOpt (provinceAlphabet, name) {
      console.log(provinceAlphabet);
      // 根据地区编码获取所在地区的JSON地图
      let path = `https://geo.datav.aliyun.com/areas_v3/bound/${provinceAlphabet}_full.json`;
      // if (provinceAlphabet === 420000) {
      //   path = "/mapJson/china.json";
      // }
      axios.get(path).then((res) => {

        // 获取完最新的JSON地图数据后,重新渲染
        echarts.registerMap(name, res.data);
        this.changeOptions(name);
        this.myChart.setOption(this.distributionOptions, true);
      }).catch((error) => {
        this.geoCounty = true
        // 请求出错时的处理逻辑 - 此时有可能是请求到县了,县的请求地址跟其他层级请求地址不一样
        this.getProvinceMapOptCounty(provinceAlphabet, name)
        // console.error('请求出错:', error);
      });
    },
    // 获取县级别的地图数据
    getProvinceMapOptCounty (provinceAlphabet, name) {
      // 根据地区编码获取所在地区的JSON地图
      let path = `https://geo.datav.aliyun.com/areas_v3/bound/${provinceAlphabet}.json`;
      axios.get(path).then((res) => {

        // 获取完最新的JSON地图数据后,重新渲染
        echarts.registerMap(name, res.data);
        this.changeOptions(name);
        this.myChart.setOption(this.distributionOptions, true);
      }).catch((error) => {
        // 请求出错时的处理逻辑 - 此时有可能是请求到县了,县的请求地址跟其他层级请求地址不一样
        console.error('请求出错:', error);
      });
    },
    // echarts 配置项
    changeOptions (name) {
      // 根据行政编码 adcode 值判断当前点位是否在此图层上 - 只有为主地图时才进行判断
      const geographicalLocation = this.geographicalCoordinates
      // 经纬度数据  --- 不存在的经纬度不会展示出来
      const seriesList = [
        {
          data: geographicalLocation,
        },
      ];
      // 图标
      const series = seriesList.map((v) => {
        return {
          type: "scatter", //配置显示方式为用户自定义
          coordinateSystem: "geo",
          data: v.data,
          // 自定义图标的样式  支持svg与bse64
          symbol: function (params, key) {
            return "image://" + require("@/assets/logo.png");
          },
          symbolSize: 16,
          tooltip: {
            trigger: 'item',
            // show:false,
            formatter: function (params) {
              // 自定义 tooltip 内容
              return `名称:${params.data.name}<br/>坐标:<br/>经度:${params.data.value[0]}<br/>纬度:${params.data.value[1]}`;
            },
          },
          clickable: true, // 允许点击
          events: {
            click: function (params) {
              // 点击事件处理函数
              console.log('点击了图标:', params.data.name);
              // 在这里可以根据点击的图标执行相应的操作
            }
          }
        };
      });

      // options
      this.distributionOptions = {
        tooltip: {},
        series, // 数据
        geo: {
          map: name || "湖北省", // 引入地图 省份或者 国家
          layoutCenter: ["50%", "50%"], //设置后left/right/top/bottom等属性无效
          layoutSize: "55%",
          roam: true, //开启鼠标缩放
          zoom: 2,
          label: {
            normal: {
              //静态的时候展示样式
              show: true, //是否显示地图省份得名称
              textStyle: {
                color: "#000",
                fontSize: 10,
                fontFamily: "Arial",
              },
            },
            emphasis: {
              // 高亮状态下的样式
              //动态展示的样式
              color: "#fff",
            },
          },
          itemStyle: {
            normal: {
              borderColor: 'rgba(147, 235, 248, 1)',
              borderWidth: 1,
              areaColor: {
                type: 'radial',
                x: 0.5,
                y: 0.5,
                r: 0.8,
                colorStops: [{
                  offset: 0,
                  color: 'rgba(147, 235, 248, 0)' // 0% 处的颜色
                }, {
                  offset: 1,
                  color: 'rgba(147, 235, 248, .2)' // 100% 处的颜色
                }],
                globalCoord: false // 缺省为 false
              },
              shadowColor: 'rgba(128, 217, 248, 1)',
              // shadowColor: 'rgba(255, 255, 255, 1)',
              shadowOffsetX: -2,
              shadowOffsetY: 2,
              shadowBlur: 10
            },
            emphasis: {
              areaColor: '#389BB7',
              borderWidth: 0
            }
          },
          regions: [
            //对不同的区块进行着色
            // {
            //   name: "河南省", //区块名称
            //   itemStyle: {
            //     normal: {
            //       areaColor: "#281fe1",
            //     },
            //   },
            // },
            // {
            //   name: "浙江省", //区块名称
            //   itemStyle: {
            //     normal: {
            //       areaColor: "#193094",
            //     },
            //   },
            // },
          ],
        },
      };
    },
  },
};
</script>


  • 18
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue 3可以通过使用ref或reactive创建响应式数据来实现动态渲染echarts图表。 首先,需要在项目中引入echarts库,可以通过npm安装echarts,然后在需要使用的组件中引入echarts: ``` import * as echarts from 'echarts'; ``` 然后,创建一个响应式对象来保存echarts的配置项和数据: ``` import { ref } from 'vue'; export default { setup() { const chartOptions = ref({ // echarts配置项 }); // 更新chartOptions数据 const updateChartOptions = () => { // 更新chartOptions的值 } return { chartOptions, updateChartOptions }; } } ``` 在模板中,可以通过v-if或v-show来控制echarts图表的显示与隐藏,将chartOptions作为echarts组件的props来动态渲染图表: ``` <template> <div> <div v-if="chartOptions"> <echarts :options="chartOptions"></echarts> </div> <button @click="updateChartOptions">更新图表</button> </div> </template> ``` 在按钮的点击事件中,可以通过调用updateChartOptions方法来更新chartOptions的值,从而实现动态渲染echarts图表: ``` import { reactive } from 'vue'; export default { setup() { const chartOptions = reactive({ // echarts配置项 }); // 更新chartOptions数据 const updateChartOptions = () => { // 更新chartOptions的值 } return { chartOptions, updateChartOptions }; } } ``` 以上是使用Vue 3进行echarts动态渲染的基本步骤,通过更新响应式对象的值,可以实现图表的动态更新。具体echarts配置项和数据处理逻辑可以根据实际需求进行调整。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值