npm install echarts
import * as echarts from 'echarts';
// 地图实例
const myChart = ref(null);
// 地图配置
const option = reactive({
tooltip: {
trigger: 'item',
formatter: function (params) {
return params.name + ':' + (params.value || 0);
},
},
series: [
// 地图配置
{
type: "map",
geoIndex: 0,
data: [{
name: '杭州市',
value: '333'
},{
name: '湖州市',
value: '444'
}],
},
],
geo: [{
map: "map_area",
layoutCenter: ['50%', '50%'],
layoutSize: '92%',
z: 2,
label: {
show: true,
fontSize: 13,
color: '#1bfeff',
},
}]
})
首先要现在HTML中定义一个有宽高的容器
<div id="mainMap" style="width: 100%;height: 100%;">div>
获取节点,初始化实例
myChart.value = echarts.init(document.getElementById('mainMap'));
监听窗口大小的变化
window.addEventListener("resize", () => {
if (myChart.value) myChart.value.resize();
})
geoJSON数据可通过接口获取,或自行下载保存到本地,自行引入,建议通过接口获取
echarts.registerMap("map_area", geoJSON);
myChart.value.setOption(option);
window.removeEventListener("resize", () => {
if (myChart.value) myChart.value.resize();
})
if (myChart.value) myChart.value.dispose()
要在实例渲染之前执行
// 点击事件
myChart.value.on('click', (mapParams) => {
console.log('click', mapParams);
});
// 鼠标移入事件
myChart.value.on('mouseover', (mapParams) => {
console.log('mouseover', mapParams);
});
// 鼠标移出事件
myChart.value.on('mouseout', (mapParams) => {
console.log('mouseout', mapParams);
});
<script setup>
import * as echarts from 'echarts';
import { onMounted, reactive, ref, onBeforeUnmount } from 'vue';
import geoJSON from './geo.json';
defineOptions({name: 'echarts'});
onMounted(() => {
loadEchartsMap();
});
// 地图实例
const myChart = ref(null);
// 地图配置
const option = reactive({
tooltip: {
trigger: 'item',
formatter: function (params) {
return params.name + ':' + (params.value || 0);
},
},
series: [
// 地图配置
{
type: "map",
geoIndex: 0,
data: [{
name: '杭州市',
value: '333'
},{
name: '湖州市',
value: '444'
}],
},
],
geo: [{
map: "map_area",
layoutCenter: ['50%', '50%'],
layoutSize: '92%',
z: 2,
label: {
show: true,
fontSize: 13,
color: '#1bfeff',
},
}]
})
// 加载Echarts地图
const loadEchartsMap = () => {
// 初始化
myChart.value = echarts.init(document.getElementById('mainMap'));
// 监听窗口大小变化
window.addEventListener("resize", () => {
if (myChart.value) myChart.value.resize();
})
// 点击事件
myChart.value.on('click', (mapParams) => {
console.log('click', mapParams);
});
// 鼠标移入事件
myChart.value.on('mouseover', (mapParams) => {
console.log('mouseover', mapParams);
});
// 鼠标移出事件
myChart.value.on('mouseout', (mapParams) => {
console.log('mouseout', mapParams);
});
// 加载地图
echarts.registerMap("map_area", geoJSON);
myChart.value.setOption(option);
}
// 销毁
onBeforeUnmount(() => {
window.removeEventListener("resize", () => {
if (myChart.value) myChart.value.resize();
})
if (myChart.value) myChart.value.dispose()
})
// 子组件暴露
defineExpose({});
</script>
<template>
<div id="mainMap" style="width: 100%;height: 100%;"></div>
</template>
<style lang="less" scoped>
</style>