1. 程式人生 > >echarts中國地圖上顯示柱狀圖,並且柱狀圖可點選

echarts中國地圖上顯示柱狀圖,並且柱狀圖可點選

先放效果圖~~


點選之後~~(資料和標題可動態變化)


話不多說,直接上程式碼

<link rel="shortcut icon" href="${ctx}/static/img/favicon.ico">
<link rel="stylesheet" href="${ctx}/static/layui_v2/css/layui.css">

<link rel="stylesheet" href="${ctx}/static/css/global.css">
<link rel="stylesheet" type="text/css"
	href="${ctx}/static/css/common.css" media="all">
<link rel="stylesheet" type="text/css"
	href="${ctx}/static/css/personal.css" media="all">
<link rel="stylesheet" href="${ctx}/static/css/main.css">

<link rel="stylesheet" type="text/css"
	href="http://at.alicdn.com/t/font_9h680jcse4620529.css">

<script src="${ctx}/static/layui_v2/layui.js"></script>

<script src="${ctx}/static/js/jquery-1.8.3.js"></script>
<script src="${ctx}/static/js/jquery.leoweather.min.js"></script>

<script type="text/javascript" src="${ctx}/static/echarts/echarts.min.js" charset="utf-8"></script>
<script type="text/javascript" src="${ctx}/static/echarts/china.js" charset="utf-8"></script>
<script type="text/javascript" src="${ctx}/static/echarts/javascript.js" charset="utf-8"></script>


</head>
<body>
<div></div>
	<div class="wrap" style="position: relative;">
		<div id="map" style="width: 100%; height: 800px;"></div>
	</div>

	<script>
	layui.use('layer', function(){ //獨立版的layer無需執行這一句
  	var $ = layui.jquery, layer = layui.layer; //獨立版的layer無需執行這一句
  
	
		var myChart = echarts.init(document.getElementById('map'));
		// 省座標,因為全國34個省固定不變,寫死即可
		var geoCoordMap = {
			'西藏' : [ 91.11, 30.97 ],
			'上海' : [ 121.48, 31.22 ],
			'福建' : [ 118.1, 27.46 ],
			'浙江' : [ 119.96, 29.86 ],
			'廣東' : [ 113.23, 24.16 ],
			'山西' : [ 112.53, 38.87 ],
			'雲南' : [ 101.73, 25.04 ],
			'遼寧' : [ 123.38, 42.8 ],
			'吉林' : [ 125.35, 44.88 ],
			'江西' : [ 115.89, 28.68 ],
			'海南' : [ 109.51, 20.25 ],
			'廣西' : [ 108.74, 24.16 ],
			'內蒙古' : [ 111.65, 42.42 ],
			'四川' : [ 104.06, 31.67 ],
			'陝西' : [ 108.95, 35.27 ],
			'江蘇' : [ 119.78, 33.04 ],
			'貴州' : [ 106.71, 27.57 ],
			'北京' : [ 116.46, 41.92 ],
			'新疆' : [ 86.68, 41.77 ],
			'山東' : [ 118, 36.65 ],
			'甘肅' : [ 103.73, 37.03 ],
			'天津' : [ 117.2, 40.13 ],
			'河南' : [ 113.65, 34.76 ],
			'黑龍江' : [ 127.63, 47.75 ],
			'河北' : [ 115.48, 40.03 ],
			'湖南' : [ 112, 28.21 ],
			'安徽' : [ 117.27, 32.86 ],
			'湖北' : [ 112.31, 31.52 ],
			'青海' : [ 97.31, 37.03 ],
			'重慶' : [ 107.31, 30.52 ],
			'寧夏' : [ 106.31, 38.52 ],
			'香港' : [ 114.31, 23.02 ],
			'澳門' : [ 114.01, 22.52 ],
			'臺灣' : [ 120.81, 25.02 ]
		};
	
	
	
		var rawData = [];
		var max1 = 0;
		//後臺獲取早中晚登入的人數
		$.post("${ctx}/main/ajax_echarts_login_info_detail.do", function(data) {
			//console.info(data.loginAfternoon[0]);
			//alert(data.province[i]);
			for (i = 0; i < data.loginAfternoon.length; i++) {
				var row = [];
				row.push(data.province[i]);
				row.push(data.loginMorning[i]);
				row.push(data.loginAfternoon[i]);
				row.push(data.loginEvening[i]);
				rawData.push(row);
			}
			;
			//console.info(rawData);
	
			//找出陣列中的最大值,用來設定柱狀圖Y軸的最大值
			//新建一個數組,將各個資料都放進去,然後查詢最大值
			var arr = [];
			for (i = 0; i < 34; i++) {
				arr.push(rawData[i][1]);
				arr.push(rawData[i][2]);
				arr.push(rawData[i][3]);
			}
			;
			//查詢陣列中最大值
	
			for (i = 0; i < arr.length; i++) {
				if (max1 < arr[i]) {
					max1 = arr[i];
				}
			}
			;
	
		
		//alert(rawData);
	
		/* ['西藏',91,11,29],
		    ['上海',91,11,29],
		    ]; */
	
	
		//產生地圖資料
		function makeMapData(rawData) {
			var mapData = [];
			for (var i = 0; i < rawData.length; i++) {
				var geoCoord = geoCoordMap[rawData[i][0]];
				if (geoCoord) {
					mapData.push({
						name : rawData[i][0],
						value : geoCoord.concat(rawData[i].slice(1))
					});
				}
			}
			return mapData;
		}
		;
	
		option = {
			animation : false,
			tooltip : {
				trigger : 'axis'
			},
			geo : {
				map : 'china',
				roam : true,
				zoom : 0.7, // 地圖初始大小
				center : [ 110.366794, 23.400309 ], // 初始中心位置
				label : {
					emphasis : {
						show : false,
						areaColor : '#eee'
					}
				},
				// 地區塊兒顏色
				itemStyle : {
					normal : {
						areaColor : '#55C3FC',
						borderColor : '#fff'
					},
					emphasis : {
						areaColor : '#21AEF8'
					}
				}
			},
			series : []
		};
	
		function renderEachCity() {
			var option = {
				xAxis : [],
				yAxis : [],
				grid : [],
				series : [],
				tooltip : {
					trigger: 'item',
					axisPointer: {
				    	type: 'none'
				    }
				}
			};
			
	
			echarts.util.each(rawData, function(dataItem, idx) {
				//console.info(idx);
				var geoCoord = geoCoordMap[dataItem[0]];
				var coord = myChart.convertToPixel('geo', geoCoord);
				idx += '';
	
				inflationData = [];
				for (var k = 1; k < 4; k++) {
					inflationData.push(dataItem[k])
				}
				;
	
				option.xAxis.push({
					id : idx,
					gridId : idx,
					type : 'category',
					name : dataItem[0],
					nameLocation : 'middle',
					nameGap : 3,
					splitLine : {
						show : false
					},
					axisTick : {
						show : false
					},
					axisLabel : {
						show : false
					},
					axisLine : {
						onZero : false,
						lineStyle : {
							color : '#666'
						}
					},
					// data: xAxisCategory,
					data : [ '早', '中', '晚' ],
					z : 100
				});
				option.yAxis.push({
					id : idx,
					gridId : idx,
					splitLine : {
						show : false
					},
					axisTick : {
						show : false
					},
					axisLabel : {
						show : false
					},
					axisLine : {
						show : false,
						lineStyle : {
							color : '#1C70B6'
						}
					},
					splitLine : {
						show : false
					},
					min : 0,
					max : max1,
					z : 100
				});
				option.grid.push({
					id : idx,
					width : 30,
					height : 40,
					left : coord[0] - 15,
					top : coord[1] - 15,
					z : 100
				});
				option.series.push({
					id : idx,
					type : 'bar',
					xAxisId : idx,
					yAxisId : idx,
					barGap : 0,
					barCategoryGap : 0,
					// data: inflationData,
					data : inflationData,
					z : 100,
					itemStyle : {
						normal : {
							color : function(params) {
								// 柱狀圖每根柱子顏色
								var colorList = [ 'red', 'green', 'yellow' ];
								return colorList[params.dataIndex];
							}
						},
						emphasis : {
							label : {
								show : false
							}
						}
					}
				});
				 
				
			});
			//console.time('a');
			myChart.setOption(option);
		//console.timeEnd('a');
		}
	
		setTimeout(renderEachCity, 0);
		// 縮放和拖拽
		function throttle(fn, delay, debounce) {
			var currCall;
			var lastCall = 0;
			var lastExec = 0;
			var timer = null;
			var diff;
			var scope;
			var args;
	
			delay = delay || 0;
	
			function exec() {
				lastExec = (new Date()).getTime();
				timer = null;
				fn.apply(scope, args || []);
			}
	
			var cb = function() {
				currCall = (new Date()).getTime();
				scope = this;
				args = arguments;
				diff = currCall - (debounce ? lastCall : lastExec) - delay;
	
				clearTimeout(timer);
				if (debounce) {
					timer = setTimeout(exec, delay);
				}
				else {
					if (diff >= 0) {
						exec();
					}
					else {
						timer = setTimeout(exec, -diff);
					}
				}
	
				lastCall = currCall;
			};
	
			return cb;
		}
	
		var throttledRenderEachCity = throttle(renderEachCity, 0);
		myChart.on('geoRoam', throttledRenderEachCity);
		myChart.setOption(option);
	
		var divObj;
		
		// 點選顯示柱狀圖
		var index;
		myChart.on('click', function(e) {
			if (e.componentSubType == "bar") {//如果選中柱狀圖,再彈出
			//多視窗模式,層疊置頂	
			if(!divObj){
				divObj = document.createElement('div');
				divObj.id = 'zhuzhuang';
				$(divObj).css({
					'width' : 250,
					'height' : 180
				}).appendTo('.wrap');
			}
				
			    zhuZhuangTu(e);
			    
			    var tanchuTitle;
			    //看彈出的是哪個省,獲取這個省份名
			    for (i = 0; i < 34; i++) {
					if (e.seriesIndex == i) {
						tanchuTitle = rawData[i][0];
					}
				};
			  
			  //判斷index是否存在,如果存在就不用open一個新的,直接更改原有的內容和標題就行
			  if(!index){
				  	index = layer.open({
			        type: 1, 
			        title: tanchuTitle,
			        id:'lid1',
			        anim: 1,
			        //area: ['250px', '180px'],
			        shade: 0,//遮罩
			        content:$('#zhuzhuang'),
			        //右上角關閉事件
			        cancel: function(){ 
	    			
	    				$('#zhuzhuang').remove();
	    				$('.layui-layer').remove();
	    				divObj=null;
	    				index=null;
	  				}
			      });
			  }
		      
		      
		      layer.title(tanchuTitle, index);//更改標題
		      
		      	//設定背景透明
		        layer.style(index, {
				   backgroundColor: 'rgba(255, 255, 255, 0.5)'
				});
			}
		});
		 /* if (e.componentSubType == "bar") {
				// 先清除所有柱狀圖
				$('.tongJiTu').remove();
	
				
				// 建立遮擋層
				//creatWrap();
				// 建立柱狀圖容器
				var divObj = document.createElement('div');
				$(divObj).addClass('tongJiTu');
				divObj.id = 'zhuzhuang';
				var divX = getMousePos()['x'];
				var divY = getMousePos()['y'];
				$(divObj).css({
					'width' : 250,
					'height' : 180,
					'border' : '1px solid #ccc',
					'position' : 'absolute',
					'top' : divY,
					'left' : divX
				}).appendTo('.wrap');
				// 建立柱狀圖
				zhuZhuangTu(e);
				
			
				// 點選遮擋層消失
				//clearWrap('.zhuzhuang');
			} */ 
		// 獲取橫縱座標
		function getMousePos(e) {
			var e = event || window.event;
			var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
			var scrollY = document.documentElement.scrollTop || document.body.scrollTop;
			var x = e.pageX || e.clientX + scrollX;
			var y = e.pageY || e.clientY + scrollY;
			// console.log(x,y)
			return {
				'x' : x,
				'y' : y
			};
		}
		// 點選彈出生成柱狀圖
		function zhuZhuangTu(e) {
			var zhuzhuang = echarts.init(document.getElementById('zhuzhuang'));
			var option = {
				backgroundColor : 'rgba(255,255,255,.5)',
				legend : {
					data : [ '早', '中', '晚' ]
				},
				xAxis : [
					{
						type : 'category',
						data : [ '早', '中', '晚' ]
					}
				],
				yAxis : [
					{
						splitLine : {
							show : false
						},
						//type: 'value',
						min : 0,
						max : max1 + 20
					}
				],
				series : [
					{
						type : 'bar',
						itemStyle : {
							normal : {
								color : function(params) {
									var colorList = [ '#F75D5D', '#59ED4F', 'yellow' ];
									return colorList[params.dataIndex];
								},
								label : {
									show : true,
									position : 'top',
									textStyle : {
										color : '#000'
									}
								}
							}
						},
						data : []
					}
				]
			};
			zhuzhuang.setOption(option);
	
			//實時獲取後臺資料,使每個省點選彈出的都是該省的資料
			var op = zhuzhuang.getOption(); //getOption: 返回內部持有的當前顯示option克隆
			for (i = 0; i < 34; i++) {
				if (e.seriesIndex == i) {
					//alert(e.seriesIndex);
					op.series[0].data.push(rawData[i][1]);
					op.series[0].data.push(rawData[i][2]);
					op.series[0].data.push(rawData[i][3]);
				}
				zhuzhuang.setOption(op, true);
			};
	
		}
		// 生成遮擋層
		function creatWrap() {
			var zheDang = document.createElement('div');
			$(zheDang).addClass('zhedang').css({
				width : '100%',
				height : '100%',
				position : 'absolute',
				top : 0,
				left : 0,
				close : true,
				backgroundColor : 'rgba(0,0,0,.2)'
			}).appendTo('.wrap');
		}
		// 去掉遮擋層
		function clearWrap(id) {
			$(id).click(function(e) {
				// console.log(this);
				this.remove();
				$('.zhuzhuang').remove();
				return false;
			});
		}
	});	
		
});
	</script>
</body>