echart地图+高德map(可下钻)

echart地图+高德map(可下钻)

高德地图和echarts结合实现可下钻的地图分布图、散点图、飞线图

gitee源码: gitee源码

echart引入教程:echart引入和组件封装-CSDN博客

1.根据区划编码调用高德api获取地理信息

1.1 引入UI组件库

UI组件库:简介 - AMapUI 组件库|高德地图API

<!--引入高德地图JSAPI -->
<script src="//webapi.amap.com/maps?v=2.0&key=您申请的key值"></script>

<!--引入UI组件库(1.1版本) -->
<script src="//webapi.amap.com/ui/1.1/main.js"></script>

1.2 加载DistrictExplorer(模块名:ui/geo/DistrictExplorer)

高德api获取初始化地理信息:AMapUI 组件库 参考手册 行政地理 行政区划浏览

/**
		 * @description 根据区划编码调用高德api获取地理信息
		 * @param {number} adcode 区划编码
		 */
getGeoJson(adcode) {
    let that = this;
    // 高德api获取初始化地理信息,详情可查看 https://lbs.amap.com/api/amap-ui/reference-amap-ui/geo/district-explorer
    // DistrictExplorer(行政区划浏览) 提供了全国范围内到区县一级的行政区划数据(含边界)
    AMapUI.loadUI(["geo/DistrictExplorer"], (DistrictExplorer) => {
        var districtExplorer = new DistrictExplorer();
        districtExplorer.loadAreaNode(adcode, function (error, areaNode) {
            // 错误信息 - error
            if (error) {
                console.error(error);
                return;
            }
            // 区域节点 - AreaNode
            // getSubFeatures() 返回该区域中全部的子级区划Feature数组
            let Json = areaNode.getSubFeatures();
            // 存在子级区域时,直接赋值
            if (Json.length > 0) {
                that.geoJson.features = Json;
            } else if (Json.length === 0) {
                // 不存在子级区域时,在原数组中筛选自己本身
                that.geoJson.features = that.geoJson.features.filter(
                    (item) => item.properties.adcode == adcode
                );
                if (that.geoJson.features.length === 0) return;
            }
            that.getMapData();
        });
    });
}
/**
		 * @description 获取并整理形成需要的数据
		 */
getMapData() {
    let mapData = this.geoJson.features.map((item) => {
        return {
            name: item.properties.name,
            value: Math.random() * 1000,
            cityCode: item.properties.adcode,
        };
    });
    // 排序,方便后续更快获取最大值和最小值
    mapData = mapData.sort(function (a, b) {
        return b.value - a.value;
    });
    this.initEcharts(mapData);
},

1.3 选择切换市县

chooseArea(val, index) {
    // 如果点击自己,直接return
    if (this.parentInfo.length === index + 1) {
        return;
    }
    //从aparentInfo索引为 index + 1 的位置开始其后面的都删除,返回的是移除的所有元素所构成的新数组
    this.parentInfo.splice(index + 1);
    this.getGeoJson(this.parentInfo[this.parentInfo.length - 1].code);
},

2.分布图

2.1 实际效果

在这里插入图片描述

2.2 echarts地图渲染


/**
		 * @description 渲染echarts
		 * @param {array} mapData 图表数据 [{name: string,value: number,cityCode:number}]
		 */
initEcharts(mapData) {
    // 获取最小值
    var min = mapData[mapData.length - 1].value;
    // 获取最大值
    var max = mapData[0].value;
    // length === 1 时默认本身为最大值,最小值取 0
    if (mapData.length === 1) {
        min = 0;
    }
    // 重绘图表时,把之前已经渲染好的图表清空,避免报错
    if (this.chart) {
        this.chart.dispose();
    }
    // 创建一个 ECharts 实例
    this.chart = echarts.init(this.$refs.DistributionMap, {
        renderer: "svg",
    });
    //注册可用的地图,只在 geo 组件或者 map 图表类型中使用
    if (this.parentInfo.length === 1) {
        echarts.registerMap("china", this.geoJson); //注册
    } else {
        echarts.registerMap("map", this.geoJson); //注册
    }
    // 设置图表实例的配置项以及数据
    this.chart.setOption(
        {
            // 背景色
            backgroundColor: "#03213D",
            // 提示框
            tooltip: {
                trigger: "item", //触发类型,数据项图形触发
                formatter: (p) => {
                    //提示框浮层内容格式器,支持字符串模板和回调函数两种形式。
                    let val = p.value;
                    if (!val) {
                        val = 0;
                    }
                    let txtCon = p.name + ":" + val.toFixed(2);
                    return txtCon;
                },
            },
            // 标题
            title: {
                show: true,
                left: "center",
                top: "15",
                text: this.parentInfo[this.parentInfo.length - 1].cityName,
                textStyle: {
                    color: "rgba(147, 235, 248, .8)",
                    fontSize: 16,
                },
            },
            // 工具栏
            toolbox: {
                // 各工具配置项
                feature: {
                    restore: {
                        //配置项还原
                        show: true, //true - 可还原地图缩放,数据栏筛选等功能
                    },
                    dataView: {
                        //数据视图
                        optionToContent: function (opt) {
                            let series = opt.series[0].data; //折线图数据
                            let div = `<div style="display: flex;align-items: center;justify-content: center;height: 100%;">`;

                            let tdHeads =
                                '<th  style="padding: 0 50px">所在地区</th><th style="padding: 0 50px">销售额</th>'; //表头
                            let tdBodys = ""; //数据
                            let table = `<table border="1" style="border-collapse:collapse;font-size:14px;text-align:left;"><tbody><tr>${tdHeads} </tr>`;
                            for (let i = 0; i < series.length; i++) {
                                table += `<tr>
                              <td style="padding: 0 50px">${series[i].name}</td>
                              <td style="padding: 0 50px">${series[
                                    i
                                ].value.toFixed(2)}万</td>
                              </tr>`;
                            }
                            table += "</tbody></table></div>";
                            return div + table;
                        },
                    },
                    saveAsImage: {
                        //保存为图片
                        name:
                        this.parentInfo[this.parentInfo.length - 1].cityName + "地图",
                    },
                    dataZoom: {
                        //数据区域缩放
                        show: false,
                    },
                    magicType: {
                        //动态类型切换
                        show: false,
                    },
                },
                // 公用的 icon 样式设置
                iconStyle: {
                    borderColor: "#1990DA", //图形的描边颜色
                },
                top: 15, //工具栏组件离容器上侧的距离
                right: 35, //工具栏组件离容器右侧的距离
            },
            // 视觉映射组件,将数据映射到视觉元素(左下方数据组件)
            visualMap: {
                min: min, //最小值
                max: max, //最大值
                left: "3%", //组件离容器左侧的距离
                bottom: "5%", // 组件离容器下侧的距离
                calculable: true, //是否显示拖拽用的手柄(手柄能拖拽调整选中范围)
                seriesIndex: [0], //指定取哪个系列的数据,即哪个系列的 series.data
                inRange: {
                    //定义 在选中范围中 的视觉元素
                    color: ["#105389", "#3a8abc", "#0D96F1"], //从高到低颜色渐变
                },
                textStyle: {
                    //文字的颜色
                    color: "#24CFF4",
                },
            },
            series: [
                {
                    name: "地图分布",
                    type: "map", //地图
                    map: this.parentInfo.length === 1 ? "china" : "map", //使用 registerMap 注册的地图名称 ,必须和 registerMap 注册的一致
                    roam: false, //是否开启鼠标缩放和平移漫游
                    zoom: 1.1, //当前视角的缩放比例
                    data: mapData,
                    label: {
                        //图形上的文本标签
                        show: true,
                        color: "rgb(249, 249, 249)", //省份标签字体颜色
                        formatter: (p) => {
                            switch (p.name) {
                                case "内蒙古自治区":
                                    p.name = "内蒙古";
                                    break;
                                case "西藏自治区":
                                    p.name = "西藏";
                                    break;
                                case "新疆维吾尔自治区":
                                    p.name = "新疆";
                                    break;
                                case "宁夏回族自治区":
                                    p.name = "宁夏";
                                    break;
                                case "广西壮族自治区":
                                    p.name = "广西";
                                    break;
                                case "香港特别行政区":
                                    p.name = "香港";
                                    break;
                                case "澳门特别行政区":
                                    p.name = "澳门";
                                    break;
                                default:
                                    break;
                            }
                            return p.name;
                        },
                    },
                    itemStyle: {
                        //地图区域的多边形 图形样式
                        areaColor: "#24CFF4",
                        borderColor: "#53D9FF",
                        borderWidth: 1.3,
                        shadowBlur: 15,
                        shadowColor: "rgb(58,115,192)",
                        shadowOffsetX: 7,
                        shadowOffsetY: 6,
                    },
                    emphasis: {
                        //高亮状态下的多边形和标签样式
                        label: {
                            show: true,
                            color: "#f75a00",
                        },
                        itemStyle: {
                            areaColor: "#8dd7fc",
                            borderWidth: 1.6,
                            shadowBlur: 25,
                        },
                    },
                },
            ],
        },
        true
    );
    let that = this;
    // 解绑鼠标点击事件处理函数,以防重复点击
    this.chart.off("click");
    // 绑定鼠标点击事件处理函数
    this.chart.on("click", (params) => {
        if (
            that.parentInfo[that.parentInfo.length - 1].code ==
            params.data.cityCode
        ) {
            return;
        }
        let data = params.data;
        that.parentInfo.push({
            cityName: data.name,
            code: data.cityCode,
        });
        that.getGeoJson(data.cityCode);
    });
},

3.散点图

3.1 实际效果

您的浏览器不支持播放该视频!

3.2 echarts地图渲染

	initEcharts(mapData) {

			// 重绘图表时,把之前已经渲染好的图表清空,避免报错
			if (this.chart) {
				this.chart.dispose()
			}
			// 创建一个 ECharts 实例
			this.chart = echarts.init(this.$refs.ScatterMap, { renderer: 'svg' });
			//注册可用的地图,只在 geo 组件或者 map 图表类型中使用

			if (this.parentInfo.length === 1) {
				echarts.registerMap('china', this.geoJson); //注册
			} else {
				echarts.registerMap('map', this.geoJson); //注册
			}
			// 设置图表实例的配置项以及数据
			this.chart.setOption({
				// 背景色
				backgroundColor: "#03213D",
				// 提示框
				tooltip: {
					trigger: "item",//触发类型,数据项图形触发
					formatter: p => {  //提示框浮层内容格式器,支持字符串模板和回调函数两种形式。
						let val = p.value[2];
						if (!val) {
							val = 0;
						}
						let txtCon = p.name + ":" + val.toFixed(2);
						return txtCon;
					}
				},
				// 标题
				title: {
					show: true,
					left: "center",
					top: "15",
					text: this.parentInfo[this.parentInfo.length - 1].cityName,
					textStyle: {
						color: "rgba(147, 235, 248, .8)",
						fontSize: 16
					}
				},
				// 工具栏
				toolbox: {
					// 各工具配置项
					feature: {
						restore: {//配置项还原
							show: true,//true - 可还原地图缩放,数据栏筛选等功能
						},
						dataView: {//数据视图
							optionToContent: function (opt) {
								let series = opt.series[0].data; //折线图数据
								let div = `<div style="display: flex;align-items: center;justify-content: center;height: 100%;">`

								let tdHeads =
									'<th  style="padding: 0 50px">所在地区</th><th style="padding: 0 50px">销售额</th>'; //表头
								let tdBodys = ""; //数据
								let table =
									`<table border="1" style="border-collapse:collapse;font-size:14px;text-align:left;"><tbody><tr>${tdHeads} </tr>`;
								for (let i = 0; i < series.length; i++) {
									table += `<tr>
                              <td style="padding: 0 50px">${series[i].name}</td>
                              <td style="padding: 0 50px">${series[i].value[2].toFixed(2)}万</td>
                              </tr>`;
								}
								table += "</tbody></table></div>";
								return div + table;
							}
						},
						saveAsImage: {//保存为图片
							name: this.parentInfo[this.parentInfo.length - 1].cityName + "地图"
						},
						dataZoom: {//数据区域缩放
							show: false
						},
						magicType: {//动态类型切换
							show: false
						}
					},
					// 公用的 icon 样式设置
					iconStyle: {
						borderColor: "#1990DA"	//图形的描边颜色
					},
					top: 15,//工具栏组件离容器上侧的距离
					right: 35//工具栏组件离容器右侧的距离
				},
				geo: {
					show: true,//是否显示地理坐标系组件
					map: this.parentInfo.length === 1 ? 'china' : 'map', //使用 registerMap 注册的地图名称 ,必须和 registerMap 注册的一致
					roam: true,//是否开启鼠标缩放和平移漫游
					zoom: 1.1, //当前视角的缩放比例
					itemStyle: {//地图区域的多边形 图形样式
						areaColor: "#105389",
						borderColor: "#53D9FF",
						borderWidth: 1.3,
						shadowBlur: 15,
						shadowColor: "rgb(58,115,192)",
						shadowOffsetX: 7,
						shadowOffsetY: 6,
					},
					emphasis: {//高亮状态下的多边形和标签样式
						label: {
							show: true,
							color: "#f75a00"
						},
						itemStyle: {
							areaColor: "#8dd7fc",
							borderWidth: 1.6,
							shadowBlur: 25
						}
					},
					label: {//图形上的文本标签
						show: true,
						color: "rgb(249, 249, 249)", //省份标签字体颜色
						formatter: p => {
							switch (p.name) {
								case "内蒙古自治区":
									p.name = "内蒙古";
									break;
								case "西藏自治区":
									p.name = "西藏";
									break;
								case "新疆维吾尔自治区":
									p.name = "新疆";
									break;
								case "宁夏回族自治区":
									p.name = "宁夏";
									break;
								case "广西壮族自治区":
									p.name = "广西";
									break;
								case "香港特别行政区":
									p.name = "香港";
									break;
								case "澳门特别行政区":
									p.name = "澳门";
									break;
								default:
									break;
							}
							// let val = p.value[2];
							// if (!val) {
							// 	val = 0;
							// }
							return p.name;
						},
					},

				},
				series: [{
					name: '散点',
					type: 'effectScatter',//类型
					data: mapData,
					coordinateSystem: 'geo',//使用地理坐标系
					showEffectOn: 'render', // 加载完毕显示特效
					symbolSize: function (val) {//设置点的大小
						return val[2] / 1.5
					},
					rippleEffect: {//涟漪特效相关配置
						number: 5, // 波纹数量
						period: 4, // 动画周期 数值越大,波动越慢
						scale: 3.5, // 动画中波纹的最大缩放比例
						brushType: 'stroke'
					},
					label: {//图形上的文本标签
						show: false,//地图上是否有文字
						formatter: p => {
							return p.value[2].toFixed()
						},
						position: 'center',
						color: '#fff'
					},
					emphasis: {//高亮的图形和标签样式
						show: false,
						scale: true
					},
					itemStyle: {//图形样式
						color: '#f9b207', //地图点的颜色
					},
					layoutCenter: ['50%', '50%'], //属性定义地图中心在屏幕中的位置,一般结合layoutSize 定义地图的大小
					layoutSize: 430
				}]
			},
				true
			);
			let that = this;
			// 解绑鼠标点击事件处理函数,以防重复点击
			this.chart.off("click");
			// 绑定鼠标点击事件处理函数
			this.chart.on("click", params => {
				console.log('params :>> ', params);
				if (!params.data) {
					return
				}
				if (
					that.parentInfo[that.parentInfo.length - 1].code ==
					params.data.cityCode
				) {
					return;
				}
				let data = params.data;
				that.parentInfo.push({
					cityName: data.name,
					code: data.cityCode
				});
				that.getGeoJson(data.cityCode);
			});
		},

4.飞线图

4.1 实际效果

您的浏览器不支持播放该视频!

4.2 echarts地图渲染

		initEcharts(mapData, lineToLf) {
			var planePath = 'path://M1705.06,1318.313v-89.254l-319.9-221.799l0.073-208.063c0.521-84.662-26.629-121.796-63.961-121.491c-37.332-0.305-64.482,36.829-63.961,121.491l0.073,208.063l-319.9,221.799v89.254l330.343-157.288l12.238,241.308l-134.449,92.931l0.531,42.034l175.125-42.917l175.125,42.917l0.531-42.034l-134.449-92.931l12.238-241.308L1705.06,1318.313z'

			// 重绘图表时,把之前已经渲染好的图表清空,避免报错
			if (this.chart) {
				this.chart.dispose()
			}
			// 创建一个 ECharts 实例
			this.chart = echarts.init(this.$refs.FlightMap, { renderer: 'svg' });
			//注册可用的地图,只在 geo 组件或者 map 图表类型中使用

			if (this.parentInfo.length === 1) {
				echarts.registerMap('china', this.geoJson); //注册
			} else {
				echarts.registerMap('map', this.geoJson); //注册
			}
			// 设置图表实例的配置项以及数据
			this.chart.setOption({
				// 背景色
				backgroundColor: "#03213D",
				// 提示框
				tooltip: {
					trigger: "item",//触发类型,数据项图形触发
					formatter: p => {  //提示框浮层内容格式器,支持字符串模板和回调函数两种形式。
						let txtCon = ''
						if (p.seriesType === "effectScatter") {
							let val = p.value[2];
							if (!val) {
								val = 0;
							}
							txtCon = p.name + ":" + val.toFixed(2);
						} else if (p.seriesType === "lines") {
							txtCon = p.data.lineToName[0] + " - " + p.data.lineToName[1]
						}
						return txtCon;
					}
				},
				// 标题
				title: {
					show: true,
					left: "center",
					top: "15",
					text: this.parentInfo[this.parentInfo.length - 1].cityName,
					textStyle: {
						color: "rgba(147, 235, 248, .8)",
						fontSize: 16
					}
				},
				// 工具栏
				toolbox: {
					// 各工具配置项
					feature: {
						restore: {//配置项还原
							show: true,//true - 可还原地图缩放,数据栏筛选等功能
						},
						dataView: {//数据视图
							optionToContent: function (opt) {
								let series = opt.series[0].data; //折线图数据
								let div = `<div style="display: flex;align-items: center;justify-content: center;height: 100%;">`

								let tdHeads =
									'<th  style="padding: 0 50px">所在地区</th><th style="padding: 0 50px">销售额</th>'; //表头
								let tdBodys = ""; //数据
								let table =
									`<table border="1" style="border-collapse:collapse;font-size:14px;text-align:left;"><tbody><tr>${tdHeads} </tr>`;
								for (let i = 0; i < series.length; i++) {
									table += `<tr>
                              <td style="padding: 0 50px">${series[i].name}</td>
                              <td style="padding: 0 50px">${series[i].value[2].toFixed(2)}万</td>
                              </tr>`;
								}
								table += "</tbody></table></div>";
								return div + table;
							}
						},
						saveAsImage: {//保存为图片
							name: this.parentInfo[this.parentInfo.length - 1].cityName + "地图"
						},
						dataZoom: {//数据区域缩放
							show: false
						},
						magicType: {//动态类型切换
							show: false
						}
					},
					// 公用的 icon 样式设置
					iconStyle: {
						borderColor: "#1990DA"	//图形的描边颜色
					},
					top: 15,//工具栏组件离容器上侧的距离
					right: 35//工具栏组件离容器右侧的距离
				},
				geo: {
					show: true,//是否显示地理坐标系组件
					map: this.parentInfo.length === 1 ? 'china' : 'map', //使用 registerMap 注册的地图名称 ,必须和 registerMap 注册的一致
					roam: true,//是否开启鼠标缩放和平移漫游
					zoom: 1.1, //当前视角的缩放比例
					itemStyle: {//地图区域的多边形 图形样式
						areaColor: "#105389",
						borderColor: "#53D9FF",
						borderWidth: 1.3,
						shadowBlur: 15,
						shadowColor: "rgb(58,115,192)",
						shadowOffsetX: 7,
						shadowOffsetY: 6,
					},
					emphasis: {//高亮状态下的多边形和标签样式
						label: {
							show: true,
							color: "#f75a00"
						},
						itemStyle: {
							areaColor: "#8dd7fc",
							borderWidth: 1.6,
							shadowBlur: 25
						}
					},
					label: {//图形上的文本标签
						show: true,
						color: "rgb(249, 249, 249)", //省份标签字体颜色
						formatter: p => {
							switch (p.name) {
								case "内蒙古自治区":
									p.name = "内蒙古";
									break;
								case "西藏自治区":
									p.name = "西藏";
									break;
								case "新疆维吾尔自治区":
									p.name = "新疆";
									break;
								case "宁夏回族自治区":
									p.name = "宁夏";
									break;
								case "广西壮族自治区":
									p.name = "广西";
									break;
								case "香港特别行政区":
									p.name = "香港";
									break;
								case "澳门特别行政区":
									p.name = "澳门";
									break;
								default:
									break;
							}
							// let val = p.value[2];
							// if (!val) {
							// 	val = 0;
							// }
							return p.name;
						},
					},

				},
				series: [
					{
						name: '散点',
						type: 'effectScatter',//类型
						data: mapData,
						coordinateSystem: 'geo',//使用地理坐标系
						showEffectOn: 'render', // 加载完毕显示特效
						symbolSize: function (val) {//设置点的大小
							return val[2] / 1.5
						},
						rippleEffect: {//涟漪特效相关配置
							number: 5, // 波纹数量
							period: 4, // 动画周期 数值越大,波动越慢
							scale: 3.5, // 动画中波纹的最大缩放比例
							brushType: 'stroke'
						},
						label: {//图形上的文本标签
							show: true,//地图上是否有文字
							formatter: p => {
								return p.value[2].toFixed()
							},
							position: 'center',
							color: '#fff'
						},
						emphasis: {//高亮的图形和标签样式
							show: false,
							scale: true
						},
						itemStyle: {//图形样式
							color: '#f9b207', //地图点的颜色
						},
						layoutCenter: ['50%', '50%'], //属性定义地图中心在屏幕中的位置,一般结合layoutSize 定义地图的大小
						layoutSize: 430
					},
					// 地图线的动画效果
					{
						type: 'lines',
						zlevel: 2,
						symbol: ['none', 'arrow'],
						// 自定义图标
						effect: {
							show: true,
							period: 6,
							trailLength: 0,
							symbol: planePath,
							symbolSize: 15
						},
						lineStyle: {
							color: 'a6c84c',
							width: 1,
							opacity: 0.6,
							curveness: 0.2
						},
						// 默认图标
						// effect: {
						// show: true,
						// period: 4, // 箭头指向速度,值越小速度越快
						// trailLength: 0.02, // 特效尾迹长度[0,1]值越大,尾迹越长重
						// symbol: 'arrow', // 箭头图标
						// symbolSize: 3, // 图标大小
						// },
						// lineStyle: {
						//     color: '#f9b207',
						//     width: 0.1, // 尾迹线条宽度
						//     opacity: 0.5, // 尾迹线条透明度
						//     curveness: 0.3 // 尾迹线条曲直度
						// },
						data: lineToLf,
						z: 3
					}]
			},
				true
			);
			let that = this;
			// 解绑鼠标点击事件处理函数,以防重复点击
			this.chart.off("click");
			// 绑定鼠标点击事件处理函数
			this.chart.on("click", params => {
				// 只有点击散点可以下钻
				if (params.seriesType !== "effectScatter") {
					return
				}
				if (!params.data) {
					return
				}
				if (
					that.parentInfo[that.parentInfo.length - 1].code ==
					params.data.cityCode
				) {
					return;
				}
				let data = params.data;
				that.parentInfo.push({
					cityName: data.name,
					code: data.cityCode
				});
				that.getGeoJson(data.cityCode);
			});
		},

5.分布散点地图

5.1 实际效果

您的浏览器不支持播放该视频!

5.2 echarts地图渲染

		/**
		 * @description 渲染echarts
		 * @param {array} mapData 图表数据 [{name: string,value: number,cityCode:number}]
		 */
		initEcharts(mapData) {
			// 获取最小值
			var min = mapData[mapData.length - 1].value[2];
			// 获取最大值
			var max = mapData[0].value[2];
			// length === 1 时默认本身为最大值,最小值取 0
			if (mapData.length === 1) {
				min = 0;
			}
			// 重绘图表时,把之前已经渲染好的图表清空,避免报错
			if (this.chart) {
				this.chart.dispose();
			}
			// 创建一个 ECharts 实例
			this.chart = echarts.init(this.$refs.AllMap, { renderer: "svg" });
			//注册可用的地图,只在 geo 组件或者 map 图表类型中使用

			if (this.parentInfo.length === 1) {
				echarts.registerMap("china", this.geoJson); //注册
			} else {
				echarts.registerMap("map", this.geoJson); //注册
			}
			// 设置图表实例的配置项以及数据
			this.chart.setOption(
				{
					// 背景色
					backgroundColor: "#03213D",
					// 提示框
					tooltip: {
						trigger: "item", //触发类型,数据项图形触发
						// formatter: p => {  //提示框浮层内容格式器,支持字符串模板和回调函数两种形式。
						// 	let val = p.value[2];
						// 	if (!val) {
						// 		val = 0;
						// 	}
						// 	let txtCon = p.name + ":" + val.toFixed(2);
						// 	return txtCon;
						// }
					},
					// 标题
					title: {
						show: true,
						left: "center",
						top: "15",
						text: this.parentInfo[this.parentInfo.length - 1].cityName,
						textStyle: {
							color: "rgba(147, 235, 248, .8)",
							fontSize: 16,
						},
					},
					grid: {
						right: "2%",
						top: "12%",
						bottom: "8%",
						width: "20%",
					},
					// 工具栏
					toolbox: {
						// 各工具配置项
						feature: {
							restore: {
								//配置项还原
								show: true, //true - 可还原地图缩放,数据栏筛选等功能
							},
							dataView: {
								//数据视图
								optionToContent: function (opt) {
									let series = opt.series[0].data; //折线图数据
									let div = `<div style="display: flex;align-items: center;justify-content: center;height: 100%;">`;

									let tdHeads =
										'<th  style="padding: 0 50px">所在地区</th><th style="padding: 0 50px">销售额</th>'; //表头
									let tdBodys = ""; //数据
									let table = `<table border="1" style="border-collapse:collapse;font-size:14px;text-align:left;"><tbody><tr>${tdHeads} </tr>`;
									for (let i = 0; i < series.length; i++) {
										table += `<tr>
                              <td style="padding: 0 50px">${series[i].name}</td>
                              <td style="padding: 0 50px">${series[
																i
															].value[2].toFixed(2)}万</td>
                              </tr>`;
									}
									table += "</tbody></table></div>";
									return div + table;
								},
							},
							saveAsImage: {
								//保存为图片
								name:
									this.parentInfo[this.parentInfo.length - 1].cityName + "地图",
							},
							dataZoom: {
								//数据区域缩放
								show: false,
							},
							magicType: {
								//动态类型切换
								show: false,
							},
						},
						// 公用的 icon 样式设置
						iconStyle: {
							borderColor: "#1990DA", //图形的描边颜色
						},
						top: 15, //工具栏组件离容器上侧的距离
						right: 35, //工具栏组件离容器右侧的距离
					},
					// 视觉映射组件,将数据映射到视觉元素(左下方数据组件)
					visualMap: {
						type: "continuous",
						min: min, //最小值
						max: max, //最大值
						left: "3%", //组件离容器左侧的距离
						bottom: "5%", // 组件离容器下侧的距离
						calculable: true, //是否显示拖拽用的手柄(手柄能拖拽调整选中范围)
						seriesIndex: [0], //指定取哪个系列的数据,即哪个系列的 series.data
						inRange: {
							//定义 在选中范围中 的视觉元素
							color: ["#24CFF4", "#2E98CA", "#1E62AC"], //从高到低颜色渐变
						},
						textStyle: {
							//文字的颜色
							color: "#24CFF4",
						},
					},
					geo: {
						show: true, //是否显示地理坐标系组件
						map: this.parentInfo.length === 1 ? "china" : "map", //使用 registerMap 注册的地图名称 ,必须和 registerMap 注册的一致
						roam: true, //是否开启鼠标缩放和平移漫游
						zoom: 1.1, //当前视角的缩放比例
						itemStyle: {
							//地图区域的多边形 图形样式
							areaColor: "#24CFF4",
							borderColor: "#53D9FF",
							borderWidth: 1.3,
							shadowBlur: 15,
							shadowColor: "rgb(58,115,192)",
							shadowOffsetX: 7,
							shadowOffsetY: 6,
						},
						emphasis: {
							//高亮状态下的多边形和标签样式
							label: {
								show: true,
								color: "#f75a00",
							},
							itemStyle: {
								areaColor: "#8dd7fc",
								borderWidth: 1.6,
								shadowBlur: 25,
							},
						},
						label: {
							//图形上的文本标签
							show: true,
							color: "rgb(249, 249, 249)", //省份标签字体颜色
							formatter: (p) => {
								switch (p.name) {
									case "内蒙古自治区":
										p.name = "内蒙古";
										break;
									case "西藏自治区":
										p.name = "西藏";
										break;
									case "新疆维吾尔自治区":
										p.name = "新疆";
										break;
									case "宁夏回族自治区":
										p.name = "宁夏";
										break;
									case "广西壮族自治区":
										p.name = "广西";
										break;
									case "香港特别行政区":
										p.name = "香港";
										break;
									case "澳门特别行政区":
										p.name = "澳门";
										break;
									default:
										break;
								}
								return p.name;
							},
						},
					},
					series: [
						{
							name: "地图分布",
							type: "map",
							geoIndex: 0,
							map: this.parentInfo.length === 1 ? "china" : "map",
							roam: true,
							zoom: 1.3,
							tooltip: {
								trigger: "item",
								formatter: (p) => {
									//提示框浮层内容格式器,支持字符串模板和回调函数两种形式。
									let txtCon = "";
									let val = p.data;
									// if (p.name == '南海诸岛') return
									if (!!val && !!val?.value) {
										txtCon =
											val.name +
											"<br />series地图数据:" +
											val.value[2].toFixed(2) +
											"万";
									} else {
										txtCon = p.name + "<br />series地图数据:" + 0.0 + "万";
									}
									return txtCon;
								},
							},
							label: {
								show: false,
							},
							emphasis: {
								label: {
									show: false,
								},
							},
							data: mapData,
						},
						{
							name: "散点",
							type: "effectScatter", //类型
							data: mapData,
							coordinateSystem: "geo", //使用地理坐标系
							showEffectOn: "render", // 加载完毕显示特效
							symbolSize: function (val) {
								//设置点的大小
								return val[2] / 1.5;
							},
							rippleEffect: {
								//涟漪特效相关配置
								number: 5, // 波纹数量
								period: 4, // 动画周期 数值越大,波动越慢
								scale: 3.5, // 动画中波纹的最大缩放比例
								brushType: "stroke",
							},
							label: {
								//图形上的文本标签
								show: false, //地图上是否有文字
							},
							emphasis: {
								//高亮的图形和标签样式
								show: false,
								scale: true,
							},
							itemStyle: {
								//图形样式
								color: "#f9b207", //地图点的颜色
							},
						},
					],
				},
				true
			);
			let that = this;
			// 解绑鼠标点击事件处理函数,以防重复点击
			this.chart.off("click");
			// 绑定鼠标点击事件处理函数
			this.chart.on("click", (params) => {
				if (!params.data) {
					return;
				}
				if (
					that.parentInfo[that.parentInfo.length - 1].code ==
					params.data.cityCode
				) {
					return;
				}
				let data = params.data;
				that.parentInfo.push({
					cityName: data.name,
					code: data.cityCode,
				});
				that.getGeoJson(data.cityCode);
			});
		},

6.完整代码

以分布图为示例,只需要把 initEcharts() 函数替换即可。

<template>
<div class="echarts">
    <div style="width: 100; height: 100%" ref="DistributionMap"></div>
    <div class="mapChoose">
        <span v-for="(item, index) in parentInfo" :key="item.code">
            <button class="button type1" @click="chooseArea(item, index)">
                {{ item.cityName == "全国" ? "中国" : item.cityName }}
    </button>
            <span
                  class="iconfont icon-xiayige"
                  v-show="index + 1 != parentInfo.length"
                  ></span>
    </span>
    </div>
    </div>
</template>

<script>
    import * as echarts from "echarts";
    import resize from "./mixins/resize";
    export default {
        name: "DistributionMap",
        mixins: [resize],
        data() {
            return {
                chart: null, //地图实列
                geoJson: {
                    //高德api获取的地理信息
                    features: [],
                },
                parentInfo: [
                    {
                        //地图列表(默认为全国-中国)
                        cityName: "全国", //
                        code: 100000, //全国的区划编码
                    },
                ],
            };
        },
        mounted() {
            // 初始化地理信息,并实例化地图
            this.$nextTick(() => {
                this.getGeoJson(100000);
            });
        },
        //页面销毁前,销毁事件和实例
        beforeDestroy() {
            if (!this.chart) {
                return;
            }
            this.chart.dispose();
            this.chart = null;
        },
        methods: {
            /**
		 * @description 根据区划编码调用高德api获取地理信息
		 * @param {number} adcode 区划编码
		 */
            getGeoJson(adcode) {
                let that = this;
                // 高德api获取初始化地理信息,详情可查看 https://lbs.amap.com/api/amap-ui/reference-amap-ui/geo/district-explorer
                // DistrictExplorer(行政区划浏览) 提供了全国范围内到区县一级的行政区划数据(含边界)
                AMapUI.loadUI(["geo/DistrictExplorer"], (DistrictExplorer) => {
                    var districtExplorer = new DistrictExplorer();
                    districtExplorer.loadAreaNode(adcode, function (error, areaNode) {
                        // 错误信息 - error
                        if (error) {
                            console.error(error);
                            return;
                        }
                        // 区域节点 - AreaNode
                        // getSubFeatures() 返回该区域中全部的子级区划Feature数组
                        let Json = areaNode.getSubFeatures();
                        // 存在子级区域时,直接赋值
                        if (Json.length > 0) {
                            that.geoJson.features = Json;
                        } else if (Json.length === 0) {
                            // 不存在子级区域时,在原数组中筛选自己本身
                            that.geoJson.features = that.geoJson.features.filter(
                                (item) => item.properties.adcode == adcode
                            );
                            if (that.geoJson.features.length === 0) return;
                        }
                        that.getMapData();
                    });
                });
            },
            /**
		 * @description 获取并整理形成需要的数据
		 */
            getMapData() {
                let mapData = this.geoJson.features.map((item) => {
                    return {
                        name: item.properties.name,
                        value: Math.random() * 1000,
                        cityCode: item.properties.adcode,
                    };
                });
                // 排序,方便后续更快获取最大值和最小值
                mapData = mapData.sort(function (a, b) {
                    return b.value - a.value;
                });
                this.initEcharts(mapData);
            },
            /**
		 * @description 渲染echarts
		 * @param {array} mapData 图表数据 [{name: string,value: number,cityCode:number}]
		 */
            initEcharts(mapData) {
                // 获取最小值
                var min = mapData[mapData.length - 1].value;
                // 获取最大值
                var max = mapData[0].value;
                // length === 1 时默认本身为最大值,最小值取 0
                if (mapData.length === 1) {
                    min = 0;
                }
                // 重绘图表时,把之前已经渲染好的图表清空,避免报错
                if (this.chart) {
                    this.chart.dispose();
                }
                // 创建一个 ECharts 实例
                this.chart = echarts.init(this.$refs.DistributionMap, {
                    renderer: "svg",
                });
                //注册可用的地图,只在 geo 组件或者 map 图表类型中使用
                if (this.parentInfo.length === 1) {
                    echarts.registerMap("china", this.geoJson); //注册
                } else {
                    echarts.registerMap("map", this.geoJson); //注册
                }
                // 设置图表实例的配置项以及数据
                this.chart.setOption(
                    {
                        // 背景色
                        backgroundColor: "#03213D",
                        // 提示框
                        tooltip: {
                            trigger: "item", //触发类型,数据项图形触发
                            formatter: (p) => {
                                //提示框浮层内容格式器,支持字符串模板和回调函数两种形式。
                                let val = p.value;
                                if (!val) {
                                    val = 0;
                                }
                                let txtCon = p.name + ":" + val.toFixed(2);
                                return txtCon;
                            },
                        },
                        // 标题
                        title: {
                            show: true,
                            left: "center",
                            top: "15",
                            text: this.parentInfo[this.parentInfo.length - 1].cityName,
                            textStyle: {
                                color: "rgba(147, 235, 248, .8)",
                                fontSize: 16,
                            },
                        },
                        // 工具栏
                        toolbox: {
                            // 各工具配置项
                            feature: {
                                restore: {
                                    //配置项还原
                                    show: true, //true - 可还原地图缩放,数据栏筛选等功能
                                },
                                dataView: {
                                    //数据视图
                                    optionToContent: function (opt) {
                                        let series = opt.series[0].data; //折线图数据
                                        let div = `<div style="display: flex;align-items: center;justify-content: center;height: 100%;">`;

                                        let tdHeads =
                                            '<th  style="padding: 0 50px">所在地区</th><th style="padding: 0 50px">销售额</th>'; //表头
                                        let tdBodys = ""; //数据
                                        let table = `<table border="1" style="border-collapse:collapse;font-size:14px;text-align:left;"><tbody><tr>${tdHeads} </tr>`;
                                        for (let i = 0; i < series.length; i++) {
                                            table += `<tr>
                              <td style="padding: 0 50px">${series[i].name}</td>
                              <td style="padding: 0 50px">${series[
                                                i
                                            ].value.toFixed(2)}万</td>
    </tr>`;
                                        }
                                        table += "</tbody></table></div>";
                                        return div + table;
                                    },
                                },
                                saveAsImage: {
                                    //保存为图片
                                    name:
                                    this.parentInfo[this.parentInfo.length - 1].cityName + "地图",
                                },
                                dataZoom: {
                                    //数据区域缩放
                                    show: false,
                                },
                                magicType: {
                                    //动态类型切换
                                    show: false,
                                },
                            },
                            // 公用的 icon 样式设置
                            iconStyle: {
                                borderColor: "#1990DA", //图形的描边颜色
                            },
                            top: 15, //工具栏组件离容器上侧的距离
                            right: 35, //工具栏组件离容器右侧的距离
                        },
                        // 视觉映射组件,将数据映射到视觉元素(左下方数据组件)
                        visualMap: {
                            min: min, //最小值
                            max: max, //最大值
                            left: "3%", //组件离容器左侧的距离
                            bottom: "5%", // 组件离容器下侧的距离
                            calculable: true, //是否显示拖拽用的手柄(手柄能拖拽调整选中范围)
                            seriesIndex: [0], //指定取哪个系列的数据,即哪个系列的 series.data
                            inRange: {
                                //定义 在选中范围中 的视觉元素
                                color: ["#105389", "#3a8abc", "#0D96F1"], //从高到低颜色渐变
                            },
                            textStyle: {
                                //文字的颜色
                                color: "#24CFF4",
                            },
                        },
                        series: [
                            {
                                name: "地图分布",
                                type: "map", //地图
                                map: this.parentInfo.length === 1 ? "china" : "map", //使用 registerMap 注册的地图名称 ,必须和 registerMap 注册的一致
                                roam: false, //是否开启鼠标缩放和平移漫游
                                zoom: 1.1, //当前视角的缩放比例
                                data: mapData,
                                label: {
                                    //图形上的文本标签
                                    show: true,
                                    color: "rgb(249, 249, 249)", //省份标签字体颜色
                                    formatter: (p) => {
                                        switch (p.name) {
                                            case "内蒙古自治区":
                                                p.name = "内蒙古";
                                                break;
                                            case "西藏自治区":
                                                p.name = "西藏";
                                                break;
                                            case "新疆维吾尔自治区":
                                                p.name = "新疆";
                                                break;
                                            case "宁夏回族自治区":
                                                p.name = "宁夏";
                                                break;
                                            case "广西壮族自治区":
                                                p.name = "广西";
                                                break;
                                            case "香港特别行政区":
                                                p.name = "香港";
                                                break;
                                            case "澳门特别行政区":
                                                p.name = "澳门";
                                                break;
                                            default:
                                                break;
                                        }
                                        return p.name;
                                    },
                                },
                                itemStyle: {
                                    //地图区域的多边形 图形样式
                                    areaColor: "#24CFF4",
                                    borderColor: "#53D9FF",
                                    borderWidth: 1.3,
                                    shadowBlur: 15,
                                    shadowColor: "rgb(58,115,192)",
                                    shadowOffsetX: 7,
                                    shadowOffsetY: 6,
                                },
                                emphasis: {
                                    //高亮状态下的多边形和标签样式
                                    label: {
                                        show: true,
                                        color: "#f75a00",
                                    },
                                    itemStyle: {
                                        areaColor: "#8dd7fc",
                                        borderWidth: 1.6,
                                        shadowBlur: 25,
                                    },
                                },
                            },
                        ],
                    },
                    true
                );
                let that = this;
                // 解绑鼠标点击事件处理函数,以防重复点击
                this.chart.off("click");
                // 绑定鼠标点击事件处理函数
                this.chart.on("click", (params) => {
                    if (
                        that.parentInfo[that.parentInfo.length - 1].code ==
                        params.data.cityCode
                    ) {
                        return;
                    }
                    let data = params.data;
                    that.parentInfo.push({
                        cityName: data.name,
                        code: data.cityCode,
                    });
                    that.getGeoJson(data.cityCode);
                });
            },

            /**
		 * @description 选择切换市县
		 * @param {object} val
		 * @param {number} index
		 */
            chooseArea(val, index) {
                // 如果点击自己,直接return
                if (this.parentInfo.length === index + 1) {
                    return;
                }
                //从aparentInfo索引为 index + 1 的位置开始其后面的都删除,返回的是移除的所有元素所构成的新数组
                this.parentInfo.splice(index + 1);
                this.getGeoJson(this.parentInfo[this.parentInfo.length - 1].code);
            },
        },
    };
</script>
<style lang="scss" scoped>
    .echarts {
        width: 100%;
        height: 100%;
        position: relative;
    }

    .mapChoose {
        position: absolute;
        left: 20px;
        top: 55px;
        color: #eee;

        .button {
            position: relative;
            padding: 8px 15px;
            border: none;
            background-color: transparent;
            cursor: pointer;
            outline: none;
            font-size: 14px;
        }

        .button.type1 {
            color: rgba(147, 235, 248, 0.8);
        }
    }
</style>
                }
                let data = params.data;
                that.parentInfo.push({
                    cityName: data.name,
                    code: data.cityCode,
                });
                that.getGeoJson(data.cityCode);
            });
        },

        /**
	 * @description 选择切换市县
	 * @param {object} val
	 * @param {number} index
	 */
        chooseArea(val, index) {
            // 如果点击自己,直接return
            if (this.parentInfo.length === index + 1) {
                return;
            }
            //从aparentInfo索引为 index + 1 的位置开始其后面的都删除,返回的是移除的所有元素所构成的新数组
            this.parentInfo.splice(index + 1);
            this.getGeoJson(this.parentInfo[this.parentInfo.length - 1].code);
        },
    },
};
```
  • 5
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值