1. 程式人生 > >獲取動態資料到echarts-折線圖

獲取動態資料到echarts-折線圖

====================html====================

<div>
    <input type="text" class="input w50" id="text" />
    <input type="text" class="input w50" id="add" />
    <button class="select" >搜尋</button>
</div>

<div class="body-content">
    <div id="bar" style="width: 800px; height: 400px;"></div>
</div>

<script src="js/bar.js"></script>

<script src="js/jquery-1.11.1.min.js" type="text/javascript"></script>
<script src="js/pintuer.js"></script>
<script src="js/echarts.js"></script>
<script src="js/jiangsu.js"></script>

<script type="text/javascript">

var lineChart;
$(function () {
    lineChart = echarts.init(document.getElementById("bar"));
//onclick="showLine()"
//初次進入頁面
showLine1();
//搜尋時用到
$(".select").click(showLine);
    
});

function showLine() {
	var path=window.document.location.href.substring(0, window.document.location.href.indexOf(window.document.location.pathname))+window.document.location.pathname.substring(0, window.document.location.pathname.substr(1).indexOf('/') + 1);
	var begtime=$("#text").val();
	var add=$("#add").val();
	//console.log("0===="+add+"==="+begtime);
    $.ajax({
        type: "POST",
        url: path+"/data/toLine", 					/* 顯示折線圖的路徑 */
        data : {"begtime":begtime,"add":add},					/* ,"add":add */
        
        dataType:"json",							
        success: function (data) {					/*  */
        	//console.log(""+data);
        	//console.log("===="+data+"==="+begtime);
            var lineOpt = getLineOpt();   			/*  */
            lineOpt.title.text = '稿件統計'; 		/*  */
            var fData = fmt.formtLineData(data);	/*  */
            lineOpt.xAxis[0].data = fData.xAxis;	/*  */
            lineOpt.series = fData.series;			/*  */
            lineChart.setOption(lineOpt);			/*  */
        }
    });
}

function showLine1() {
	var path=window.document.location.href.substring(0, window.document.location.href.indexOf(window.document.location.pathname))+window.document.location.pathname.substring(0, window.document.location.pathname.substr(1).indexOf('/') + 1);
	/* var begtime=$("#text").val();
	var add=$("#add").val(); */
	//console.log("1===="+"===");
    $.ajax({
        type: "POST",
        url: path+"/data/toLine", 					/* 顯示折線圖的路徑 */
       //data : {"begtime":begtime,"add":add},					/* ,"add":add */
        
        dataType:"json",							
        success: function (data) {					/*  */
        	//console.log(""+data);
        	//console.log("===="+data+"==="+begtime);
            var lineOpt = getLineOpt();   			/*  */
            lineOpt.title.text = '稿件統計'; 		/*  */
            var fData = fmt.formtLineData(data);	/*  */
            lineOpt.xAxis[0].data = fData.xAxis;	/*  */
            lineOpt.series = fData.series;			/*  */
            lineChart.setOption(lineOpt);			/*  */
        }
    });
}

</script>

=====================bar.js======================== 

function initMapGeoJson(jsonUrl, mType, mId) {
    var mapChart;
    $.ajax({
        type: "POST",
        url: jsonUrl,
        dataType:"json",
        async: false,
        success: function (mJson) {
            echarts.registerMap(mType, mJson);
            mapChart = echarts.init(document.getElementById(mId));
        }
    });
    return mapChart;
}

var fmt = {
		formtLineData: function (data) {
	        var xAxis = [];
	        var group = [];
	        var series = [];
	        var type = 'line';

	        for (var i = 0; i < data.length; i++) {
	            for (var j = 0; j < xAxis.length && xAxis[j] != data[i].name; j++);
	            if (j == xAxis.length) {
	                xAxis.push(data[i].name);
	            }
	            for (var k = 0; k < group.length && group[k] != data[i].group; k++);
	            if (k == group.length) {
	                group.push(data[i].group);
	            }
	        }

	        for (var i = 0; i < group.length; i++) {
	            var tData = [];
	            var valMap = {};

	            for (var j = 0; j < data.length; j++) {
	                if (group[i] == data[j].group) {
	                    valMap[data[j].name] = data[j].value;
	                }
	            }

	            for (var n = 0; n < xAxis.length; n++) {
	                tData.push(valMap[xAxis[n]]);
	            }

	            var tSeries = {
	                name: group[i],
	                data: tData,
	                type: type
	            };

	            series.push(tSeries);
	        }

	        return {
	            category: group,
	            xAxis: xAxis,
	            series: series
	        };
	    }
};

//折線圖
function getLineOpt() {
    // 基於準備好的dom,初始化echarts例項
   // var myChart = echarts.init(document.getElementById('bar'));

// 指定圖表的配置項和資料
	lineOpt = {
	    title: {
	        show: true,
            text: '',
            subtext: ''
        },
        tooltip: {
            trigger: 'axis'
        },
        legend: {
            data:['瀏覽量','下載量','評論量','點贊量']
        },
        toolbox: {
            show: true,
            feature: {
                dataZoom: {
                    yAxisIndex: 'none'
                },
                dataView: {readOnly: true},
                magicType: {type: ['line', 'bar']},
                restore: {},
                saveAsImage: {}
            }
        },
        xAxis:  [{
            type: 'category',
            boundaryGap: false,
            data: []
        }],
        yAxis: [{
            type: 'value',
            axisLabel: {
                formatter: '{value} 次'
            }
        }],
        series: []
    };
    // 資料處理
    return lineOpt;
}




=====================控制層========================

        //首次進入html
        @RequestMapping("/toStat")  
	public ModelAndView toLine(HttpServletRequest request) {  
	    return new ModelAndView("forward:/WEB-INF/views/admin/data/data-stat.jsp");  
	} 

	// 跳轉到資料分析-稿件統計-折線圖
	@RequestMapping("/toLine")
	@ResponseBody
	public List<HashMap<String, Object>> toStat(String add,String begtime,Model model, HttpServletRequest request) throws ParseException {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("begtime", begtime);
		map.put("add", add);
		String dateString;
		
		List<HashMap<String, Object>> lList=null;
		List<String> rqList=null;
		
		if(begtime != null && begtime != ""){
	    	model.addAttribute("begtime", begtime);
	    	Calendar cal = Calendar.getInstance();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
			cal.setTime(sdf.parse(begtime)); 
	    	dateString=sdf.format(cal.getTime());
			 
			 rqList = new ArrayList<String>();
			 for (int i = 0; i < 6; i++) {
				 dateString=sdf.format(cal.getTime());
			  
				 rqList.add(dateString.substring(0, 7));
				 
				 cal.add(Calendar.MONTH, -1);
			 }
	    }
		else{
			 Calendar cal = Calendar.getInstance();
			 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
			 dateString = sdf.format(cal.getTime());
			 model.addAttribute("begtime", dateString);
			 rqList = new ArrayList<String>();
			 for (int i = 0; i < 6; i++) {
				 dateString = sdf.format(cal.getTime());
				 rqList.add(dateString.substring(0, 7));
				 
				 cal.add(Calendar.MONTH, -1);
				 
			 }
		}
		
		//字串轉時間
		ArrayList<Date> dateList = new ArrayList<Date>();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
		for (String str : rqList) {
			try {
				dateList.add(format.parse(str));
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		
		//氣泡排序
		Date tempDate = null;
		for (int i = dateList.size()- 1; i > 0; --i) {
            for (int j = 0; j < i; ++j) {
            	
            	//從小到大
            	tempDate = dateList.get(j);
            	dateList.set(j, dateList.get(j+1));
            	dateList.set(j+1, tempDate);
            	
            }
        }
		
		//時間轉字串
		ArrayList<String> dateList1 = new ArrayList<String>();
		for (Date str : dateList) {
			try {
				dateList1.add(format.format(str));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
//		System.out.println("排序後:");
//		for(String d:dateList1){
//			System.out.println(d);
//		}
		
		List<Log_Great> artRefNumList0=new ArrayList<Log_Great>();
	    for(String a :dateList1){
	    	Log_Great artRefNum=new Log_Great();
			artRefNum.setTime(a);
			map.put("greattime",artRefNum.getTime());
			map.put("add", add);
		    List<Integer> artbrnum=dataService.getDataGreatBrCount(map);
		    List<Integer> artbrnum2=dataService.getDataGreatBrCount2(map);
		    for(Integer s:artbrnum){
			    for(Integer s2:artbrnum2){
				    int i=s+s2;
				    //System.out.println("=========i:"+i);
				    artRefNum.setGreatNum(i);
			    }
		    }
		   
		    artRefNumList0.add(artRefNum);
		}
	    
	    List<Log_Browse> artRefNumList1=new ArrayList<Log_Browse>();
	    for(String a :dateList1){
	    	Log_Browse artRefNum=new Log_Browse();
	    	artRefNum.setTime(a);
			map.put("brtime",artRefNum.getTime());
			map.put("add", add);
		    List<Integer> artbrnum=dataService.getDataBrowByCount(map);
		    List<Integer> artbrnum2=dataService.getDataBrowByCount2(map);
		    for(Integer s:artbrnum){
			   for(Integer s2:artbrnum2){
				   int i=s+s2;
				   //System.out.println("=========i:"+i);
				   artRefNum.setBrNum(i);
			   }
		    }
		   
		    artRefNumList1.add(artRefNum);
		}
	    
	    List<Log_Download> artRefNumList2=new ArrayList<Log_Download>();
	    for(String a :dateList1){
	    	Log_Download artRefNum=new Log_Download();
	    	artRefNum.setTime(a);
			map.put("downtime",artRefNum.getTime());
			map.put("add", add);
		    List<Integer> artbrnum=dataService.getDataDownByCount(map);
		    List<Integer> artbrnum2=dataService.getDataDownByCount2(map);
		    for(Integer s:artbrnum){
		    	for(Integer s2:artbrnum2){
					int i=s+s2;
					//System.out.println("=========i:"+i);
					artRefNum.setDownNum(i);
				}
		    }
		   
		    artRefNumList2.add(artRefNum);
		}
	    
	    List<Log_comment> artRefNumList3=new ArrayList<Log_comment>();
	    for(String a :dateList1){
	    	Log_comment artRefNum=new Log_comment();
	    	artRefNum.setTime(a);
			map.put("commtime",artRefNum.getTime());
			map.put("add", add);
		    List<Integer> artbrnum=dataService.getDataCommByCount(map);
		    List<Integer> artbrnum2=dataService.getDataCommByCount2(map);
		    for(Integer s:artbrnum){
			    for(Integer s2:artbrnum2){
				    int i=s+s2;
				    //System.out.println("=========i:"+i);
				    artRefNum.setCommNum(i);
			    }
		    }
		   
		    artRefNumList3.add(artRefNum);
		}
	    
	    lList = JsonResult.getLineRndVal(dateList1,artRefNumList0,artRefNumList1,artRefNumList2,artRefNumList3);
            return lList;
	}

=================工具類=================

package com.utils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.Map.Entry;

import com.xinhuajs.articlemg.model.Log_Browse;
import com.xinhuajs.articlemg.model.Log_Download;
import com.xinhuajs.articlemg.model.Log_Great;
import com.xinhuajs.articlemg.model.Log_comment;
import com.xinhuajs.articlemg.model.Log_login;

    public class JsonResult implements Serializable{

	private static final long serialVersionUID = 7754981695162962186L;
    
	private Object data;

	public JsonResult() {
		super();
		// TODO Auto-generated constructor stub
	}

	public JsonResult(Object data) {
		super();
		this.data = data;
	}
	
	//==============================ECharts圖表的折線圖=====================
    public static List<String> splStr2List(Integer str, String spl) {
        String[] strs = null;
        List<String> strList = null;
        if (str != null) {
            strs = str.toString().split(spl);
            if (strs != null) {
                strList = new ArrayList<String>();
                for (String st : strs) {
                    strList.add(st != null ? st.trim() : "");
                }
            }
        }
        return strList;
    }
    public static List<String> splStr2List(String str, String spl) {
        String[] strs = null;
        List<String> strList = null;
        if (str != null) {
            strs = str.split(spl);
            if (strs != null) {
                strList = new ArrayList<String>();
                for (String st : strs) {
                    strList.add(st != null ? st.trim() : "");
                }
            }
        }
        return strList;
    }

	 public static List<HashMap<String, Object>> getLineRndVal(List<String> dateString,List<Log_Great> list,List<Log_Browse> brlist,List<Log_Download> dolist,List<Log_comment> comlist) {
		 List<HashMap<String, Object>> lists = new ArrayList<HashMap<String, Object>>();

		 for(Log_Great a :list){
	        List<String> date = splStr2List(a.getTime(), ",");
	        List<String> name = splStr2List("點贊量", ",");
	        List<String> num = splStr2List(a.getGreatNum(), ",");
	        for (String grp : name) {
	            for (String nam : date) {
	            	for (String count : num) {
	            		HashMap<String, Object> vals = new HashMap<String, Object>();
	                	vals.put("group", grp);
	                	vals.put("name", nam);
	                	vals.put("value", count); 
	                	lists.add(vals);
	            	}
	            }
	        }
		 }
		 
		 for(Log_Browse a :brlist){
		     List<String> date = splStr2List(a.getTime(), ",");
		     List<String> name = splStr2List("瀏覽量", ",");
		     List<String> num = splStr2List(a.getBrNum(), ",");
		     for (String grp : name) {
		         for (String nam : date) {
		        	 for (String count : num) {
		        		 HashMap<String, Object> vals = new HashMap<String, Object>();
		                 vals.put("group", grp);
		                 vals.put("name", nam);
		                 vals.put("value", count);
		                 lists.add(vals);
		            }
		        }
			 }
		 }
		 for(Log_Download a :dolist){
		     List<String> date = splStr2List(a.getTime(), ",");
		     List<String> name = splStr2List("下載量", ",");
		     List<String> num = splStr2List(a.getDownNum(), ",");
		     for (String grp : name) {
		    	 for (String nam : date) {
		    		 for (String count : num) {
		            	 HashMap<String, Object> vals = new HashMap<String, Object>();
		                 vals.put("group", grp);
		                 vals.put("name", nam);
		                 vals.put("value", count);
		                 lists.add(vals);
		            }
		        }
			 }
		 }
		 
		 for(Log_comment a :comlist){
		        
			 List<String> date = splStr2List(a.getTime(), ",");
		     List<String> name = splStr2List("評論量", ",");
		     List<String> num = splStr2List(a.getCommNum(), ",");
		     for (String grp : name) {
		    	 for (String nam : date) {
		    		 for (String count : num) {
		            	 HashMap<String, Object> vals = new HashMap<String, Object>();
		                 vals.put("group", grp);
		                 vals.put("name", nam);
		                 vals.put("value", count);
		                 lists.add(vals);
		            }
		        }
			 }
		 }
		 
	     return lists;
	 }
	 
	 
	
	//=======================================

	public Object getData() {
		return data;
	}

	public void setData(Object data) {
		this.data = data;
	}

	@Override
	public String toString() {
		return "JsonResult [data=" + data + "]";
	}
	
	
}