本文主要是介绍【vue3 + Echarts 】中国地图省市区下钻,并返回上级,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
实现效果如果:
echarts版本:
地图数据来源:阿里云数据可视化平台
代码
<template><div class="mapWrapper"><a-button type="primary" @click="goBack">返回上级</a-button><div ref="mapChartRef" style="height: 100%; width: 100%"></div></div>
</template><script setup>
import axios from "axios";
import { ref, onMounted } from "vue";
import * as echarts from "echarts";const mapChartRef = ref();
const initChinaMap = ref();
const initAdCode = ref(100000); // 默认中国地图的编码
const currentMapName = ref("中国"); // 默认地图的名称
const mapList = ref([]); // 当前展示的省市区所有数据
const historyInfo = ref([]); // 记录历史点击的省市区,用于返回查询// 获取地图数据
const getMapData = async (code) => {const data = await axios.get(`https://geo.datav.aliyun.com/areas_v3/bound/${code}_full.json`).then((res) => {mapList.value = [];if (res.status === 200) {// 获取当前选中的省市区的所有名称和编码res.data.features.forEach((item) => {mapList.value.push(item.properties);});renderChart(currentMapName.value, res.data);}}).catch(() => {});return data;
};// 渲染地图
const renderChart = (mapName, mapData) => {// 注册: registerMap('地图名称', 地图数据), 地图名称须和option里面的map一致echarts.registerMap(mapName, mapData);// 地图配置项const option = {// 提示浮窗样式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",},showDelay: 100,formatter: (params) => {return params.name;},},series: [{type: "map",map: mapName, // 地图名称data: [],zoom: "1.1", // 当前视角的缩放比例label: {show: true, // 是否显示省份名字},roam: false, // 是否开启缩放和平移itemStyle: {borderColor: "#F59A23", // 边界线颜色borderType: "dashed", // 边界线类型},// 设置鼠标移上去高亮的样式emphasis: {itemStyle: {borderColor: "#34AEAE",areaColor: "#CCEBEB",borderType: "solid",},},},],};// 渲染initChinaMap.value.setOption(option);// 防止多次触发click事件,重要!!!initChinaMap.value.off("click");// 下钻initChinaMap.value.on("click", (params) => {const activeItem = mapList.value.find((item) => item.name == params.name);// 判断有子级的时候才可以下钻if (activeItem && activeItem.adcode && activeItem.childrenNum) {historyInfo.value.push(activeItem);currentMapName.value = params.name;getMapData(activeItem.adcode);}});
};onMounted(() => {initChinaMap.value = echarts.init(mapChartRef.value);getMapData(initAdCode.value);
});// 返回上一级
const goBack = () => {const lastItem = historyInfo.value.pop();if (lastItem && lastItem.parent && lastItem.parent.adcode) {getMapData(lastItem.parent.adcode);}
};
</script><style scoped>
.mapWrapper {width: 700px;height: 600px;padding: 10px;border: 1px dashed orange;
}
</style>
这篇关于【vue3 + Echarts 】中国地图省市区下钻,并返回上级的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!