用Echart創建簡單的折線圖

wKiom1h4kSSAaDlZAACgg0MpYLM705.png-wh_50

<%@ page language="java" contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>機組耗電量統計圖</title>

<link rel="stylesheet" href="${path }/public/layui/css/layui.css">

<link rel="stylesheet" href="${path }/public/css/style.css">

<script type="text/javascript" src="${path }/public/layui/layui.js"></script>

<script src="${path }/public/layui/lay/lib/jquery.js"></script>

<script src="${path }/public/layui/lay/dest/layui.all.js"></script>

<script src="${path }/public/js/jquery-1.4.4.min.js"></script>

<script>

layui.use('element', function() {

var $ = layui.jquery, element = layui.element(); //Tab的切換功能,切換事件監聽等,需要依賴element模塊


//觸發事件          

var active = {

tabAdd : function() {

//新增一個Tab項

element.tabAdd('demo', {

title : '新選項' + (Math.random() * 1000 | 0) //用於演示

,

content : '內容' + (Math.random() * 1000 | 0)

})

},

tabDelete : function() {

//刪除指定Tab項

element.tabDelete('demo', 2); //刪除第3項(注意序號是從0開始計算)

},

tabChange : function() {

//切換到指定Tab項

element.tabChange('demo', 1); //切換到第2項(注意序號是從0開始計算)

}

};


$('.site-demo-active').on('click', function() {

var type = $(this).data('type');

active[type] ? active[type].call(this) : '';

});

});

</script>

</head> 

<body>

<div class="layui-tab layui-tab-card">

<ul class="layui-tab-title">

<li id="power_day">日</li>

<li id="power_month">月</li>

<li id="power_year">年</li>

</ul>

<div class="layui-tab-content" style="height: 350px;">

    <div class="layui-tab-item layui-show">

         <div id="mainone" style="height:380px"></div>

    </div>

    <div class="layui-tab-item layui-show">     

<div id="maintwo" style="height:380px"></div>

</div>

    <div class="layui-tab-item layui-show">

<div id="mainthree" style="height:380px"></div>

</div>

</div>

</div>

</body>

<!-- ECharts單文件引入 -->

<script src="${path }/public/js/echarts.js"></script>

<script type="text/javascript">

// 路徑配置

require.config({

paths : {

echarts : 'http://echarts.baidu.com/build/dist'

}

});


// 使用

require([ 'echarts', 'echarts/chart/line' // 使用柱狀圖就加載bar模塊,按需加載 (需修改爲相應的圖形名稱)

], function(ec) {

// 基於準備好的dom,初始化echarts圖表

var myChart = ec.init(document.getElementById('mainone'));

   var myChartMonth = ec.init(document.getElementById('maintwo')); 

var myChartYear = ec.init(document.getElementById('mainthree'));

loadEchartPower(myChart,1);

//日耗電量

var dayObj = document.getElementById("power_day");

dayObj.addEventListener("click", function(){

loadEchartPower(myChart,1);

}, true);

//月耗電

var monthObj = document.getElementById("power_month");

monthObj.addEventListener("click", function(){

loadEchartPower(myChartMonth,2);

}, true); 

//年耗電

var yearObj = document.getElementById("power_year");

yearObj.addEventListener("click", function(){

loadEchartPower(myChartYear,3);

}, true);

});

//機組及蒸發器功率

function loadEchartPower(myChart, type){

var index = layer.load(2, {shade: false},{time: 5*1000}); //0代表加載的風格,支持0-2   添加加載層

$.ajax({

url:path+'/chart/aircrewTmep',

dataType:'json',

type:'post',

data:{coding:'${coding}',type:type},

success:function(data){

//console.log(JSON.stringify(data.series));

//console.log(data.legend);

layer.close(index); //關閉加載層

/*

var legendArr = ['蒸發器1','蒸發器2','蒸發器3','機組1'];

var seriesArr = [{"name":"蒸發器1","type":"line","stack":null,

"data":["0.5","1.00","1.20","1.00","2.50","1.50","4.00","2.50","3.00","1.00","2.00","1.00","2.30","4.00"],"smooth":false},

{"name":"蒸發器2","type":"line","stack":null,

"data":["1.00","1.2","1.5","1.8","2.0","1.5","1.2","2.2","2.3","1.5","2.5","2.8","3.0","3.5"],"smooth":false},

{"name":"蒸發器3","type":"line","stack":null,

"data":["1.2","1.5","1.8","2.0","1.8","1.5","2.2","2.5","2.7","2.0","1.9","2.63","2.8","3.7"],"smooth":false},

{"name":"機組1","type":"line","stack":null,

"data":["2.0","1.2","1.5","1.8","2.1","1.6","1.3","1.8","1.4","1.5","1.6","2.3","3.5","4.0"],"smooth":false}];

*/

option = {

title : {

text : '機組耗電量統計圖',

subtext : '時間/耗電量'

},

tooltip : {

trigger : 'axis'

},

legend : {

data : data.legend

},

                    toolbox: {

                        show : true,

                        feature : {

                            mark : {show: true},

                            dataView : {show: true, readOnly: false},

                            magicType : {show: true, type: ['line', 'bar', 'stack', 'tiled']},

                            restore : {show: true},

                            saveAsImage : {show: true}

                        }

                    },

calculable : true,

xAxis : [ {

type : 'category',

boundaryGap : false,

data : data.time

} ],

yAxis : [ {

type : 'value'

} ],

series : data.series,

};

// 爲echarts對象加載數據

myChart.setOption(option);

}

});

}

</script>

</html>


<!-----------------------------JAVA後臺代碼----------------------------------------->

@Controller

@RequestMapping("/chart")

public class ChartCtrl {

@Autowired

private ChartService chartService;

/**

 * 機組耗電量

 */

@RequestMapping("/aircrewTmep")

@ResponseBody

public Map<String, Object> aircrewTmep(HttpSession session,HttpServletRequest req){

HashMap<String, Object> rlt = new HashMap<>();

try {

Object identityCode = session.getAttribute("identity_code");

if(identityCode==null||"".equals(identityCode)){

return null;

}

String type = req.getParameter("type");

HashMap<String, String> map = new HashMap<>();

map.put("identity_code", identityCode.toString());

map.put("coding", req.getParameter("coding"));

rlt=chartService.aircrewTmep(map, type);

} catch (Exception e) {

e.printStackTrace();

}

return rlt;

}

}


@Service

public class ChartService {

public HashMap<String, Object> aircrewTmep(HashMap<String, String> map,String type){

HashMap<String, Object> rlt = new HashMap<>();

List<ChactSeriesVO> chartserieslist = new ArrayList<>();

List<String> legendlist = new ArrayList<>();

String json = null;

String[] timeArr = null;

try {

if(1==Integer.parseInt(type)){ //日

map.put("day", DateTools.createDate());

json = HttpClientUtil.httpPost("http://localhost:8080/test/app/running/day/", map, "utf-8");

}else if(2==Integer.parseInt(type)){ //月

map.put("day", DateTools.yearMonth());

json = HttpClientUtil.httpPost("http://localhost:8080/test/app/running/month/", map, "utf-8");

}else{ //年

map.put("day", DateTools.nowYear());

json = HttpClientUtil.httpPost("http://localhost:8080/test/app/running/year/", map, "utf-8");

}

System.out.println("---json---"+json);

if(json != null){

ObjectMapper mapper = new ObjectMapper();

JsonNode tree = mapper.readTree(json);

JsonNode evaporatorList = tree.findValue("data").findPath("evaporator");

for (int i = 0; i < evaporatorList.size(); i++) {

JsonNode chart = evaporatorList.get(i);

JsonNode evaplist = chart.findPath("power");

ChactSeriesVO aevo = new ChactSeriesVO();

aevo.setName(chart.get("title").asText());

aevo.setType("line");

aevo.setSmooth(false);

aevo.setData(tempArr(evaplist));

chartserieslist.add(aevo);

legendlist.add(chart.get("title").asText());

}

JsonNode aircrewlist = tree.findValue("data").findValue("aircrew").findPath("power");

ChactSeriesVO tempaevo = new ChactSeriesVO();

tempaevo.setName(tree.findValue("data").findValue("aircrew").findValue("title").asText());

tempaevo.setType("line");

tempaevo.setSmooth(false);

tempaevo.setData(tempArr(aircrewlist));

chartserieslist.add(tempaevo);

legendlist.add(tree.findValue("data").findValue("aircrew").findValue("title").asText());

JsonNode timelist = tree.findValue("data").findPath("time");

timeArr = new String[timelist.size()];

for (int m = 0; m < timelist.size(); m++) {

String strtime = DateTools.stampToDate(timelist.get(m).asText());

if(1==Integer.parseInt(type)){

timeArr[m] = DateTools.strToHour(strtime);

}else if(2==Integer.parseInt(type)){

timeArr[m] = DateTools.strToDate(strtime);

}else{

timeArr[m] = DateTools.strToMonth(strtime);

}

}

//System.out.println("---evaporatorList--"+evaporatorList);

}

} catch (Exception e) {

e.printStackTrace();

}

rlt.put("time", timeArr);

rlt.put("series", chartserieslist);

rlt.put("legend", legendlist);

return rlt;

}

//字符串數組賦值

public String[] tempArr(JsonNode templist){

String[] powerarr = new String[templist.size()];

for (int i = 0; i < templist.size(); i++) {

powerarr[i] = new String(templist.get(i).asText());

}

return powerarr;

}

}


/*****************----series對應的實體類----固定字段---方便頁面取值-----***********************/


package com.shangyukeji.icoolcloud.vo;

public class ChactSeriesVO {


private String name;

private String type;

private String stack;

private String[] data;

private boolean smooth;

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getType() {

return type;

}

public void setType(String type) {

this.type = type;

}

public String getStack() {

return stack;

}

public void setStack(String stack) {

this.stack = stack;

}

public String[] getData() {

return data;

}

public void setData(String[] data) {

this.data = data;

}

public boolean isSmooth() {

return smooth;

}

public void setSmooth(boolean smooth) {

this.smooth = smooth;

}

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章