Vue实现疫情地图
Vue实现疫情地图的基本步骤
安装必要的依赖库,如axios用于数据请求,echarts或leaflet用于地图渲染。
npm install axios echarts --save
获取疫情数据
通过公开的疫情数据API获取最新数据,例如使用腾讯或丁香园的接口。使用axios发起GET请求。
import axios from 'axios';
async function fetchEpidemicData() {
try {
const response = await axios.get('https://api.tianapi.com/ncov/index?key=YOUR_API_KEY');
return response.data.result;
} catch (error) {
console.error('Error fetching data:', error);
return null;
}
}
初始化ECharts地图
在Vue组件的mounted钩子中初始化ECharts实例,并配置地图选项。
import * as echarts from 'echarts';
export default {
data() {
return {
chart: null,
epidemicData: []
};
},
async mounted() {
this.epidemicData = await fetchEpidemicData();
this.initChart();
},
methods: {
initChart() {
this.chart = echarts.init(this.$refs.mapContainer);
const option = {
title: {
text: '全国疫情地图'
},
tooltip: {
trigger: 'item',
formatter: '{b}: {c}例'
},
visualMap: {
min: 0,
max: 1000,
text: ['High', 'Low'],
realtime: false,
calculable: true,
inRange: {
color: ['#f6efa6', '#d94e5d']
}
},
series: [{
name: '确诊人数',
type: 'map',
map: 'china',
data: this.epidemicData,
label: {
show: true
}
}]
};
this.chart.setOption(option);
}
}
};
模板部分
在Vue模板中添加一个容器用于渲染地图。
<template>
<div ref="mapContainer" style="width: 800px; height: 600px;"></div>
</template>
响应式调整
监听窗口大小变化,动态调整图表尺寸。
mounted() {
window.addEventListener('resize', this.handleResize);
},
methods: {
handleResize() {
if (this.chart) {
this.chart.resize();
}
}
},
beforeDestroy() {
window.removeEventListener('resize', this.handleResize);
}
数据更新
定期或手动刷新数据,更新地图显示。
methods: {
async refreshData() {
this.epidemicData = await fetchEpidemicData();
this.chart.setOption({
series: [{
data: this.epidemicData
}]
});
}
}
注意事项
确保在组件销毁时释放ECharts实例,避免内存泄漏。

beforeDestroy() {
if (this.chart) {
this.chart.dispose();
}
}





