1、下载echarts
cnpm install echarts --save-dev
2、在main.js中全局引入
import echarts from 'echarts'
Vue.prototype.$echarts = echarts
3、准备js或json文件
echarts默认只提供世界地图、中国地图和省份地图,如果需要城市地图则需要下载json文件,转换为js
下载地址如下:
链接:https://download.csdn.net/download/weixin_39150852/12267613
4、定义echarts-map组件并使用
<template>
<div class="echarts-map-div">
<div ref="myEchart" class="echarts"></div>
</div>
</template>
<script>
import '../../assets/js/china'
export default {
name: 'EchartsMap',
data() {
return {
index: 0,
myChart: null,
mTime: null
}
},
mounted() {
this.drawMap()
this.setHighlight()
this.mouseEvents()
},
methods: {
drawMap() {
this.myChart = this.$echarts.init(this.$refs.myEchart)
this.myChart.setOption({
backgroundColor: 'transparent', // 地图背景色
geo: {
map: 'china', // 地区名
roam: true,//平移或缩放
label: {
normal: {
show: true,
color: 'rgba(255, 255, 255, 0.5)'
},
emphasis: {
color: '#fff'
}
},
itemStyle: {
areaColor: '#226DA4',
borderColor: 'rgba(255, 255, 255, 0.5)'
},
regions: [] //对不同的区块进行着色
}
})
},
setHighlight(isHighlight = true, name = '') {
let option = this.myChart.getOption()
//获取区块列表
const regionsData = option.geo[0].regions
if (isHighlight) {//定时器设置区块依次高亮
this.mTime = setInterval(() => {
option.geo[0].regions = [{
name: regionsData[this.index].name, //区块名称
label: { color: '#fff' },
itemStyle: { areaColor: '#188FFE' }
}]
this.myChart.setOption(option)
this.index++
if (this.index === regionsData.length) {
this.index = 0
}
}, 2000)
} else {//鼠标移入区块高亮,其他区块恢复默认颜色
let arr = option.geo[0].regions.map(item => {
if (name !== '' && item.name === name) {
return {
name: item.name,
label: { color: '#fff' },
itemStyle: { areaColor: '#188FFE' }
}
} else {
return { name: item.name }
}
})
option.geo[0].regions = arr
this.myChart.setOption(option)
}
},
mouseEvents() {
// 鼠标划入
this.myChart.on('mouseover', (e) => {
// 停止定时器,清除之前的高亮
clearInterval(this.mTime)
this.mTime = null
this.setHighlight(false, e.name)
})
// 鼠标划出重新定时器开始
this.myChart.on('mouseout', () => {
this.setHighlight()
})
}
}
}
</script>
<style scoped lang="less">
.echarts-map-div {
width: 100vw;
height: 100vh;
background-color: rgba(0, 0, 0, 0.9);
display: flex;
align-items: center;
justify-content: center;
overflow: hidden;
.echarts {
width: 80%;
height: 80%;
}
}
</style>
json文件转换为js文件
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['exports', 'echarts'], factory);
} else if (typeof exports === 'object' && typeof exports.nodeName !== 'string') {
// CommonJS
factory(exports, require('echarts'));
} else {
// Browser globals
factory({}, root.echarts);
}
}(this, function (exports, echarts) {
var log = function (msg) {
if (typeof console !== 'undefined') {
console && console.error && console.error(msg);
}
}
if (!echarts) {
log('ECharts is not Loaded');
return;
}
if (!echarts.registerMap) {
log('ECharts Map is not loaded')
return;
}
echarts.registerMap('地区名',json文件的内容)
}));