目标:
这周我们学习了百度图表Echars的使用,第一阶段利用数据库数据生成统计图,第二三阶段利用数据生成全国确诊人数分布图。主要实现方法如下:
1.连接数据库,读取数据返回一个List,servlet调用这个函数,以json格式传回给前端页面。
2.前端页面接收数据
第一阶段代码:
Dao:
public class DataDao {// public List<Data> search(String beginyear, String endyear) throws SQLException {// QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());// String sql = “select * from info where date >= ? and date <= ?”;// return runner.query(sql, new BeanListHandler<Data>(Data.class),beginyear,endyear);// }//}
public List<Data> search1(String beginyear,String endyear){
int num=0;
List<Data>list=new ArrayList<Data>();
Connection con=null;
java.sql.Statement psts=null;
ResultSet rs=null;
try {
con=DataDB.getCon();
String sql=”select * from info where Date between ‘”+beginyear+”‘ and ‘”+endyear+”‘”;
System.out.print(sql);
psts=con.createStatement();
rs=psts.executeQuery(sql);
while(rs.next()){
String id=rs.getString(“Id”);
String date=rs.getString(“Date”);
String province=rs.getString(“Province”);
String city=rs.getString(“City”);
String confirmed_num=rs.getString(“Confirmed_num”);
String yisi_num=rs.getString(“Yisi_num”);
String cured_num=rs.getString(“Cured_num”);
String dead_num=rs.getString(“Dead_num”);
Data data=new Data(id,date,province,city,confirmed_num,yisi_num,cured_num,dead_num);
list.add(data);
}
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append(“Served at: “).append(request.getContextPath());
request.setCharacterEncoding(“utf-8”);
response.setContentType(“text/html;charset=utf-8”);
String beginyearString=request.getParameter(“beginyear”);
String endyearString=request.getParameter(“endyear”);
List<Data>list=new ArrayList<Data>();
DataDao dataDao=new DataDao();
list=dataDao.search1(beginyearString, endyearString);
if (list!=null) {
System.out.print(“查询成功“);
request.setAttribute(“list”, list);
request.getRequestDispatcher(“show.jsp”).forward(request, response);
}
}
show.jsp(需要一个search页面按照前后两个时间搜索,在这里不展出)
<%@ page language=”java” contentType=”text/html; charse=tUTF-8″
pageEncoding=”UTF-8″%>
<%@page import=”java.util.List”%>
<%@page import=”echart.Data”%>
<%@taglib uri=”http://java.sun.com/jsp/jstl/core” prefix=”c” %><!DOCTYPE html><html><head><meta charset=”UTF-8″><title>信息显示页面</title></head>
<!– 引入 echarts.js –>
<script src=”https://cdn.staticfile.org/echarts/4.3.0/echarts.min.js”></script> //在这里引入echars.js的地址,这里写的是网络地址,也可以下载后写入此文件在整个工程中的地址
<script type=”text/javascript”>
</script>
</head><body>
<% request.setCharacterEncoding(“utf-8”);
List <Data> provinces =(List<Data>) request.getAttribute(“list”); //接收后台传过来的数据集合int i=0;%><div align=”center”>
<div id=”main” align=”center” style=”width: 750px;height:430px;” >//首先为统计图规定一个容器
<script type=”text/javascript”>
var myChart = echarts.init(document.getElementById(‘main’));
var option = {
dataset: {
source: [
[ ‘省份‘,’确诊人数‘],
<%
//获取request域中的数据
if(provinces!=null){
for(Data province:provinces){i++;
%>
[‘<%=province.getProvince()%>’,'<%=province.getConfirmed_num()%>’],//将list中的数据拼接成json格式作为要显示在统计图中的数据
<%
if(i>33)break;
}
}
%>
]
},
grid: {containLabel: true},
xAxis: {type: ‘category’},
yAxis: {},
series: [
{
type: ‘bar’,//此处决定了统计图类型,bar:柱状图,line:折线图
encode: {
// 将 “amount” 列映射到 X 轴。 x: ‘省份‘,
// 将 “product” 列映射到 Y 轴。 y: ‘确诊人数‘
}
}]
};
// 使用刚指定的配置项和数据显示图表。 myChart.setOption(option);
</script>
</div>
</div>
<table><tr>
<td>省份</td>
<td>确诊人数</td>
<td>时间</td></tr><c:forEach items=”${list }” var=”list”><tr>
<td>${list.province }</td>
<td>${list.confirmed_num }</td>
<td>${list.date }</td></tr></c:forEach></table>
</body></html>
第二阶段代码:
Dao:
public static List search2(String data) {
int num=0;
List<Data>list=new ArrayList<Data>();
Connection con=null;
java.sql.Statement psts=null;
ResultSet rs=null;
try {
con=DataDB.getCon();
String sql=”select * from info1 where Date ='”+data+”‘”;
System.out.print(sql);
psts=con.createStatement();
rs=psts.executeQuery(sql);
while(rs.next()){
String id=rs.getString(“Id”);
String date=rs.getString(“Date”);
String province=rs.getString(“Province”);
String city=rs.getString(“City”);
String confirmed_num=rs.getString(“Confirmed_num”);
String yisi_num=rs.getString(“Yisi_num”);
String cured_num=rs.getString(“Cured_num”);
String dead_num=rs.getString(“Dead_num”);
Data data1=new Data(id,date,province,city,confirmed_num,yisi_num,cured_num,dead_num);
list.add(data1);
}
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding(“UTF-8”);
response.setCharacterEncoding(“UTF-8”);
String dataString=request.getParameter(“time”);
List<Data>list=new ArrayList<Data>();
DataDao dataDao=new DataDao();
list=dataDao.search2(dataString);
if(list!=null) {
Gson gson = new Gson();
String json = gson.toJson(list);
System.out.println(json);
response.getWriter().write(json);//阶段一是将list传回给前台,在前台进行拼接,阶段二直接将json格式的数据传回给前台
}
}
map.<!DOCTYPE html><html style=”height: 100%”>
<head><meta charset=”UTF-8″><base><title>地图阶段二</title><script src=”js/jquery-1.12.3.min.js” type=”text/javascript”></script><script type=”text/javascript” src=”js/echarts.js”></script><script type=”text/javascript” src=”js/china.js”></script></head><body style=”height: 100%; margin: 0″>
<div class=”row” style=” height: 50px”>
日期 <input type=”text” name=”time”
id=”time” placeholder=”yyyy-MM-dd hh:mm:ss”> <input
type=”button” value=”查询“ onclick=”tu()”>//为查询按钮绑定了一个函数,实现了利用ajax异步读取交换数据
</div>
<div id=”main” style=”height: 100%”></div></body><script type=”text/javascript”>
function randomData() {
return Math.round(Math.random() * 500);
}
var dt;
var mydata1 = new Array(0);
function tu() {
time = $(“#time”).val();
//alert(time.substring(0, 2)); $.ajax({
url : “InfoServlet”,//要传送的servlet地址,此处即为传给InfoServlet
async : true,
type : “POST”,
data : {
“time” : time//要穿送的数据,为jason格式
},
success : function(data) {//执行成功的回调函数,此处即为显示地图
dt = data;
for (var i = 0; i < 33; i++) {
var d = {
};
d[“name”] = dt[i].province;//.substring(0, 2); d[“value”] = dt[i].confirmed_num;
d[“yisi_num”] = dt[i].yisi_num;
d[“cured_num”] = dt[i].cured_num;
d[“dead_num”] = dt[i].dead_num;
mydata1.push(d);
}//接收后台的数据
//var mdata = JSON.stringify(mydata1);
var optionMap = {
backgroundColor : ‘#FFFFFF’,
title : {
text : ‘全国地图大数据‘,
subtext : ”,
x : ‘center’
},
//echart提示框内容:
tooltip : {
formatter : function(params) {
return params.name + ‘<br/>’ + ‘确诊人数 : ‘
+ params.value + ‘<br/>’ + ‘死亡人数 : ‘
+ params[‘data’].dead_num + ‘<br/>’ + ‘治愈人数 : ‘
+ params[‘data’].cured_num + ‘<br/>’+ ‘疑似患者人数 : ‘
+ params[‘data’].yisi_num;
}//数据格式化 },
//左侧小导航图标 visualMap : {
min : 0,
max : 35000,
text : [ ‘多‘, ‘少‘ ],
realtime : false,
calculable : true,
inRange : {
color : [ ‘lightskyblue’, ‘yellow’, ‘orangered’ ]
}
},
//配置属性 series : [ {
type : ‘map’,
mapType : ‘china’,
label : {
show : true
},
data : mydata1,
nameMap : {
‘南海诸岛‘ : ‘南海诸岛‘,
‘北京‘ : ‘北京市‘,
‘天津‘ : ‘天津市‘,
‘上海‘ : ‘上海市‘,
‘重庆‘ : ‘重庆市‘,
‘河北‘ : ‘河北省‘,
‘河南‘ : ‘河南省‘,
‘云南‘ : ‘云南省‘,
‘辽宁‘ : ‘辽宁省‘,
‘黑龙江‘ : ‘黑龙江省‘,
‘湖南‘ : ‘湖南省‘,
‘安徽‘ : ‘安徽省‘,
‘山东‘ : ‘山东省‘,
‘新疆‘ : ‘新疆维吾尔自治区‘,
‘江苏‘ : ‘江苏省‘,
‘浙江‘ : ‘浙江省‘,
‘江西‘ : ‘江西省‘,
‘湖北‘ : ‘湖北省‘,
‘广西‘ : ‘广西壮族自治区‘,
‘甘肃‘ : ‘甘肃省‘,
‘山西‘ : ‘山西省‘,
‘内蒙古‘ : “内蒙古自治区“,
‘陕西‘ : ‘陕西省‘,
‘吉林‘ : ‘吉林省‘,
‘福建‘ : ‘福建省‘,
‘贵州‘ : ‘贵州省‘,
‘广东‘ : ‘广东省‘,
‘青海‘ : ‘青海省‘,
‘西藏‘ : ‘西藏自治区‘,
‘四川‘ : ‘四川省‘,
‘宁夏‘ : ‘宁夏回族自治区‘,
‘海南‘ : ‘海南省‘,
‘台湾‘ : ‘台湾‘,
‘香港‘ : ‘香港‘,
‘澳门‘ : ‘澳门‘
}
} ]
};
//初始化echarts实例
var myChart = echarts.init(document.getElementById(‘main’));
//使用制定的配置项和数据显示图表 myChart.setOption(optionMap);
},
error : function() {
alert(“请求失败“);
},
dataType : “json”
});
}</script></html>
阶段三代码:
根据题目要求,点击全国省级地图后,要能进行市级地图展示并能够显示市级确诊人数。
实现过程,在阶段二的前端代码中为地图添加点击的监听函数,能够实现点击后利用servlet向下一个页面跳转
跳转后加载市级地图,然后利用ajax实现提示框市级信息的展示。
Dao:
public static List search3(String data,String province) {
int num=0;
List<Data>list=new ArrayList<Data>();
Connection con=null;
java.sql.Statement psts=null;
ResultSet rs=null;
try {
con=DataDB.getCon();
String sql=”select * from info1 where Date ='”+data+”‘ and Province ='”+province+”‘”;
System.out.print(sql);
psts=con.createStatement();
rs=psts.executeQuery(sql);
while(rs.next()){
String id=rs.getString(“Id”);
String date=rs.getString(“Date”);
String city=rs.getString(“City”);
String confirmed_num=rs.getString(“Confirmed_num”);
String yisi_num=rs.getString(“Yisi_num”);
String cured_num=rs.getString(“Cured_num”);
String dead_num=rs.getString(“Dead_num”);
Data city2=new Data(id,date,province,city,confirmed_num,yisi_num,cured_num,dead_num);
list.add(city2);
}
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
servlet1:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append(“Served at: “).append(request.getContextPath());
request.setCharacterEncoding(“utf-8”);
response.setContentType(“text/html;charset=utf-8”);
String time=request.getParameter(“time”);
String provinceString=request.getParameter(“province”);
request.setAttribute(“province”, provinceString);
System.out.print(“成功“);
request.getRequestDispatcher(“littlemap.jsp”).forward(request, response);
}
servlet2:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append(“Served at: “).append(request.getContextPath());
request.setCharacterEncoding(“UTF-8”);
response.setCharacterEncoding(“UTF-8”);
String dataString=”2020-02-12 10:14:15″;
String province = request.getParameter(“province”);
List<Data>list=new ArrayList<Data>();
List<Data>listcityCities=new ArrayList<Data>();
DataDao dataDao=new DataDao();
list=dataDao.search3(dataString,province);
for(int i=0;i<list.size();i++) {
Data data=new Data();
data.setCity(list.get(i).getCity());
data.setConfirmed_num(list.get(i).getConfirmed_num());
listcityCities.add(data);
}
Gson gson = new Gson();
String json = gson.toJson(listcityCities);
System.out.println(json);
response.getWriter().write(json);
System.out.println();
}
map1.html
<!DOCTYPE html><html style=”height: 100%”>
<head><meta charset=”UTF-8″><base><title>地图阶段二</title><script src=”js/jquery-1.12.3.min.js” type=”text/javascript”></script><script type=”text/javascript” src=”js/echarts.js”></script><script type=”text/javascript” src=”js/china.js”></script></head><body style=”height: 100%; margin: 0″>
<div class=”row” style=” height: 50px”>
日期 <input type=”text” name=”time”
id=”time” placeholder=”yyyy-MM-dd hh:mm:ss”> <input
type=”button” value=”查询“ onclick=”tu()”>
</div>
<div id=”main” style=”height: 100%”></div></body><script type=”text/javascript”>
function randomData() {
return Math.round(Math.random() * 500);
}
var dt;
var mydata1 = new Array(0);
function tu() {
time = $(“#time”).val();
//alert(time.substring(0, 2)); $.ajax({
url : “InfoServlet”,
async : true,
type : “POST”,
data : {
“time” : time
},
success : function(data) {
dt = data;
for (var i = 0; i < 33; i++) {
var d = {
};
d[“name”] = dt[i].province;//.substring(0, 2); d[“value”] = dt[i].confirmed_num;
d[“yisi_num”] = dt[i].yisi_num;
d[“cured_num”] = dt[i].cured_num;
d[“dead_num”] = dt[i].dead_num;
mydata1.push(d);
}
//var mdata = JSON.stringify(mydata1);
var optionMap = {
backgroundColor : ‘#FFFFFF’,
title : {
text : ‘全国地图大数据‘,
subtext : ”,
x : ‘center’
},
tooltip : {
formatter : function(params) {
return params.name + ‘<br/>’ + ‘确诊人数 : ‘
+ params.value + ‘<br/>’ + ‘死亡人数 : ‘
+ params[‘data’].dead_num + ‘<br/>’ + ‘治愈人数 : ‘
+ params[‘data’].cured_num + ‘<br/>’+ ‘疑似患者人数 : ‘
+ params[‘data’].yisi_num;
}//数据格式化 },
//左侧小导航图标 visualMap : {
min : 0,
max : 35000,
text : [ ‘多‘, ‘少‘ ],
realtime : false,
calculable : true,
inRange : {
color : [ ‘lightskyblue’, ‘yellow’, ‘orangered’ ]
}
},
//配置属性 series : [ {
type : ‘map’,
mapType : ‘china’,
label : {
show : true
},
data : mydata1,
nameMap : {
‘南海诸岛‘ : ‘南海诸岛‘,
‘北京‘ : ‘北京市‘,
‘天津‘ : ‘天津市‘,
‘上海‘ : ‘上海市‘,
‘重庆‘ : ‘重庆市‘,
‘河北‘ : ‘河北省‘,
‘河南‘ : ‘河南省‘,
‘云南‘ : ‘云南省‘,
‘辽宁‘ : ‘辽宁省‘,
‘黑龙江‘ : ‘黑龙江省‘,
‘湖南‘ : ‘湖南省‘,
‘安徽‘ : ‘安徽省‘,
‘山东‘ : ‘山东省‘,
‘新疆‘ : ‘新疆维吾尔自治区‘,
‘江苏‘ : ‘江苏省‘,
‘浙江‘ : ‘浙江省‘,
‘江西‘ : ‘江西省‘,
‘湖北‘ : ‘湖北省‘,
‘广西‘ : ‘广西壮族自治区‘,
‘甘肃‘ : ‘甘肃省‘,
‘山西‘ : ‘山西省‘,
‘内蒙古‘ : “内蒙古自治区“,
‘陕西‘ : ‘陕西省‘,
‘吉林‘ : ‘吉林省‘,
‘福建‘ : ‘福建省‘,
‘贵州‘ : ‘贵州省‘,
‘广东‘ : ‘广东省‘,
‘青海‘ : ‘青海省‘,
‘西藏‘ : ‘西藏自治区‘,
‘四川‘ : ‘四川省‘,
‘宁夏‘ : ‘宁夏回族自治区‘,
‘海南‘ : ‘海南省‘,
‘台湾‘ : ‘台湾‘,
‘香港‘ : ‘香港‘,
‘澳门‘ : ‘澳门‘
}
} ]
};
});
//使用制定的配置项和数据显示图表 myChart.setOption(optionMap);
},
error : function() {
alert(“请求失败“);
},
dataType : “json”
});
}</script></html>
littlemap.jsp
<%@ page language=”java” contentType=”text/html; charset=UTF-8″
pageEncoding=”UTF-8″%><!DOCTYPE html><html><head><meta charset=”UTF-8″><title>Insert title here</title><script src=”js/jquery-1.12.3.min.js” type=”text/javascript”></script><script type=”text/javascript” src=”js/echarts.js”></script><script type=”text/javascript” src=”js/china.js”></script></head><body>
var myChart = echarts.init(document.getElementById(‘main’));//myChart.showLoading();var province = “${province}”;//var list = “${list}”;
$.get(“mapjson/”+ province +”.json”, function (geoJson) {
myChart.hideLoading();
echarts.registerMap(province, geoJson);
myChart.setOption(option = {
title: {
text: province + ‘地区疫情情况‘,
},
tooltip: {
trigger: ‘item’,
formatter: ‘{b}<br/>{c}人确诊‘
},
toolbox: {
show: true,
orient: ‘vertical’,
left: ‘right’,
top: ‘center’,
feature: {
dataView: {readOnly: false},
restore: {},
saveAsImage: {}
}
},
visualMap: {
min: 0,
max: 50000,
text: [‘High’, ‘Low’],
inRange: {
color: [‘lightskyblue’, ‘yellow’, ‘orangered’]
}
}
]
});
});
$.ajax({
url:”servlet2″,
async:true,
type:”POST”,
data:{“province”:province},
success:function(data){
alert(data.length);
alert(data.city);
var mydata1 = new Array(0);
for(var i=0;i<data.length;i++){
var c = {};
c[“name”] = data[i].city+’市‘;
c[“value”] = data[i].confirmed_num;
mydata1.push(c);
}
alert(mydata1.size);
myChart.setOption({ //加载数据图表 series: [{
data: mydata1
}]
});
},
error:function(){
alert(“请求失败“);
},
dataType:”json”
});
</script></body></html>
原文链接:https://www.cnblogs.com/zl00/p/13088162.html
原创文章,作者:优速盾-小U,如若转载,请注明出处:https://www.cdnb.net/bbs/archives/2782