<template>
<div id="main"></div>
<button v-if="isDeep" @click="backToLastMap()">返回上一层</button>
</template>
<script setup>
import { onMounted, ref } from 'vue';
import * as echarts from 'echarts';
import axios from 'axios';
import { message } from 'ant-design-vue';
const myChart = ref();
const isDeep = ref(false);
const historyMapData = ref([]);
const chartMap = () => {
myChart.value = echarts.init(document.getElementById('main'));
initMap(myChart, '中华人民共和国', '100000', false);
myChart.value.on('click', (e) => {
const provinceName = e.name;
const provinceAdcode = e.data.value.adcode;
if (provinceAdcode !== '100000') {
isDeep.value = true;
}
initMap(myChart, provinceName, provinceAdcode);
});
};
// 返回上一级
const backToLastMap = () => {
historyMapData.value.pop();
const lastMapData = historyMapData.value[historyMapData.value.length - 1];
const { geoName, adcode } = lastMapData;
if (adcode === '100000') {
isDeep.value = false;
}
initMap(myChart, geoName, adcode);
};
// 初始化地图
const initMap = async (chartDOM, geoName, adcode) => {
chartDOM.value.showLoading();
// 获取地图JSON数据,注册地图。
try {
const mapData = await getMapJSON(adcode, geoName);
if (historyMapData.value.findIndex((i) => i.adcode === adcode) == -1) {
historyMapData.value.push({ geoName, adcode });
}
// 获取地图配置项,生成地图
const option = getOption(geoName, mapData);
chartDOM.value.setOption(option);
} catch (error) {
return message.info('已经是最后一层了。');
} finally {
chartDOM.value.hideLoading();
}
};
let a = '';
// 获取地图数据
const getMapJSON = async (adcode = '100000', geoName) => {
if (adcode === a) {
throw new Error('已经是最后一层了。');
}
const res = await axios.get(
`https://geo.datav.aliyun.com/areas_v2/bound/${adcode}_full.json`
);
a = adcode;
echarts.registerMap(geoName, res.data);
const mapData = res.data.features.map((item) => {
return {
value: item.properties,
name: item.properties.name,
};
});
return mapData;
};
// 获取地图配置
const getOption = (geoName, mapData) => {
const option = {
title: { text: geoName },
tooltip: {
trigger: 'item',
},
series: [
{
type: 'map',
map: geoName,
data: mapData,
},
],
animation: true,
};
return option;
};
onMounted(() => {
chartMap();
});
</script>
<style>
#main {
width: 80%;
height: 600px;
}
</style>
用Vue3+echarts实现可下钻地图(到市)
于 2024-01-09 17:34:56 首次发布