背景
年纪大了,记性就不大好。这不,虽然之前弄过不止一次的echarts地图,但最近在做的时候还是耽误了不少时间,古语有云
好记性不如烂笔头
如此便记录下
本文框架基于Vue 2.x,echarts 4.9
Vue模版
<template>
<div class="page" style="height: 100%">
<div ref="map" style="height: 100%" />
</div>
</template>
方式1,series map + 地图js
首先,引入echarts自带的地图js文件,引入后会自动注册地图名字和数据
import echarts from 'echarts'
import 'echarts/map/js/china'
import 'echarts/map/js/province/shanghai'
然后执行初始化和option数据组合
watch: {
//监听option变化,然后重新绘制地图
mapOption: {
handler() {
this.update()
},
deep: true
}
},
mounted() {
this.init()
this.map()
},
methods: {
init() {
const el = this.$refs.map
this.chart = echarts.init(el)
},
map(name = 'china') {
// 可以通过name切换不同的区域
this.mapOption = {
series: [
{
type: 'map',
map: name
}
]
}
},
update() {
if (this.chart && this.mapOption && this.mapOption) {
try {
this.chart.setOption(this.mapOption, true, false)
} catch (e) {
// console.log(e)
}
}
}
}
效果如下:
这种方式会有一个问题,就是echarts的版本要低于echarts 5,因为echarts5中的地图js数据被删除了,无法引入
方式2,geo + 地图json
这个方式类似第一种,区别在于需要先注册地图,因此我们先获取地图json,这里我建议从DataV处获取地图json
获取到地图json后,保存在assets/datavjson下
// 其他类似方式1,这里仅展示不同部分
map(name = '中华人民共和国') {
echarts.registerMap(name, require(`@/assets/datavjson/${name}.json`))
this.mapOption = {
geo: {
map: name,
zoom: 1.23
}
}
},
效果如下:
方式3,echarts + 百度地图api
因为需要百度地图api,故首先应该申请百度地图ak(开发者),然后在public/index.html中引入百度地图api
接着在vue文件中引入bmap的拓展即可,bmap的数据复制于官方demo中,也可以在百度地图的文档中找到地图样式的数据。
import 'echarts/extension/bmap/bmap'
// methods
map() {
this.mapOption = {
bmap: {
center: [104.114129, 37.550339],
zoom: 5,
roam: true,
mapStyle: {
styleJson: [
{
featureType: 'water',
elementType: 'all',
stylers: {
color: '#d1d1d1'
}
},
{
featureType: 'land',
elementType: 'all',
stylers: {
color: '#f3f3f3'
}
},
{
featureType: 'railway',
elementType: 'all',
stylers: {
visibility: 'off'
}
},
{
featureType: 'highway',
elementType: 'all',
stylers: {
color: '#fdfdfd'
}
},
{
featureType: 'highway',
elementType: 'labels',
stylers: {
visibility: 'off'
}
},
{
featureType: 'arterial',
elementType: 'geometry',
stylers: {
color: '#fefefe'
}
},
{
featureType: 'arterial',
elementType: 'geometry.fill',
stylers: {
color: '#fefefe'
}
},
{
featureType: 'poi',
elementType: 'all',
stylers: {
visibility: 'off'
}
},
{
featureType: 'green',
elementType: 'all',
stylers: {
visibility: 'off'
}
},
{
featureType: 'subway',
elementType: 'all',
stylers: {
visibility: 'off'
}
},
{
featureType: 'manmade',
elementType: 'all',
stylers: {
color: '#d1d1d1'
}
},
{
featureType: 'local',
elementType: 'all',
stylers: {
color: '#d1d1d1'
}
},
{
featureType: 'arterial',
elementType: 'labels',
stylers: {
visibility: 'off'
}
},
{
featureType: 'boundary',
elementType: 'all',
stylers: {
color: '#fefefe'
}
},
{
featureType: 'building',
elementType: 'all',
stylers: {
color: '#d1d1d1'
}
},
{
featureType: 'label',
elementType: 'labels.text.fill',
stylers: {
color: '#999999'
}
}
]
}
},
}
},
效果如下:
结束
至此,三种基于echarts的地图已全部介绍完毕,各有利弊吧,下一步,便可以在地图之上绘制散点图,迁徙图之类的了。