引言
今天用百度地图和echarts,实现多点连接。
展示
![](https://img2020.cnblogs.com/blog/1800266/202106/1800266-20210616200845958-398158777.png)
前端html
<!DOCTYPE html>
<html class="x-admin-sm">
<head>
<meta charset="UTF-8">
<title>欢迎页面-X-admin2.2</title>
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width,user-scalable=yes, minimum-scale=0.4, initial-scale=0.8,target-densitydpi=low-dpi" />
<link rel="stylesheet" href="/static/css/font.css">
<link rel="stylesheet" href="/static/css/xadmin.css">
<link rel="stylesheet" href="../static/layui/css/layui.css" media="all">
<script src="../static/layui/layui.js" charset="utf-8"></script>
<script type="text/javascript" src="/static/js/xadmin.js"></script>
<script type="text/javascript" src="/static/js/jquery-3.3.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/echarts/dist/echarts.min.js"></script>
<script type="text/javascript" src="/static/js/bmap.js"></script>
<script type="text/javascript" src="https://api.map.baidu.com/getscript?v=你申请的key"></script>
<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=你申请的key"></script>
{# <script src="https://cdn.jsdelivr.net/npm/echarts/dist/extension/bmap.min.js"></script>#}
{# <script src="https://cdn.jsdelivr.net/npm/echarts/map/js/china.js"></script>#}
<!-- 让IE8/9支持媒体查询,从而兼容栅格 -->
<!--[if lt IE 9]>
<script src="https://cdn.staticfile.org/html5shiv/r29/html5.min.js"></script>
<script src="https://cdn.staticfile.org/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
<title>地图展示</title>
</head>
<body>
<h1 align="center"><blockquote class="layui-elem-quote">在本页面查看结构物的所有有害生物。</blockquote></h1>
<div id="main" style="100%;height:800px"></div>
<div id="allmap"></div>
</body>
<script type="text/javascript">
var bmapChart = echarts.init(document.getElementById('main'));
{#var bmapChart = new BMap.Map("main");#}
{#bmapChart.centerAndZoom(new BMap.Point(116.404, 39.915), 11);#}
{#var walking = new BMap.WalkingRoute(bmapChart, {renderOptions:{map: bmapChart, autoViewport: true}});#}
{#walking.search("天坛公园", "故宫");#}
// 检测对象数据
let zuobiao = {{ zuobiao | tojson }};
//首先先定义需要显示对应信息的位置坐标,按照[纬度,精度]的格式
let geo_data = {};
{% for row in zuobiao %}
geo_data["{{ row['name']}}"] = [{{ row['lng'] }},{{ row['lat'] }}];
{% endfor %}
let geoCoordMap = geo_data;
let convertData = function (data) {
var res = [];
for (var i = 0; i < data.length; i++) {
var geoCoord = geoCoordMap[data[i].name]; //首先根据data中的name作为键值读入地理坐标
if (geoCoord) {
res.push({
name: data[i].name,
value: geoCoord.concat(data[i].value), //随后将地理坐标与对应信息值衔接起来
insect_names:data[i].insect_names
});
}
}
return res;
};
//线条颜色
var colors = ["#00A0E9", "#F29B76", "#F76B8F", "#6DF3AC", "#CF42E8", "#F1EA24"];
var option = {
title:{
text:'害虫分布地图'
},
legend: {
data: ['害虫严重程度'], // 要对应series的name
opsition: "center", // 图例位置
},
tooltip : {
trigger: "item" //提示框
},
bmap: {
center: [116.307698, 40.056975], // 初始化中心位置坐标
zoom: 5, // 地图缩放比例
roam: true // 开启用户缩放
},
};
// 实例化地图
bmapChart.setOption(option);
//地图点线传输动画效果
let ods = [];
//坐标点集合
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';
{% for one in similar_region %}
temp = [];
{% for i in one %}
{% if not loop.last %}
temp.push({
insectName:"{{ i["insect_name"] }}",
fromName: "{{ i["name"] }}",
toName: "{{ one[loop.index]["name"] }}",
coords: [[{{ i["longitude"] }}, {{ i["latitude"] }}], [{{ one[loop.index]["longitude"] }},{{ one[loop.index]["latitude"] }}]]
});
{% endif %}
{% endfor %}
ods.push(temp);
{% endfor %}
option.series = [
{
name: '害虫严重程度',
type: 'effectScatter', // 特效散点图,也可用普通散点图scatter
coordinateSystem: 'bmap', // 坐标系使用bmap,以地图作为底图
data: convertData(zuobiao),
symbolSize: function (val) {
return val[2] * 2; // 用值的大小调整点的大小
},
encode: {
value: 2
},
label: {
formatter: '{c}',
position: 'right',
show: false
},
tooltip:{
trigger: "item", //提示框
formatter: function (item) {
let msg = "<h2>城市名称:"+item["name"]+"</h2><br>";
msg += "<h3>相关害虫名称:"+item["data"]["insect_names"]+"</h3><br>";
msg += "<h3>害虫个数:"+item["data"]["value"][2]+"</h3><br>";
return msg;
}
},
itemStyle: {
color:function(params){
let value = params["value"][2];
if (value>=1 && value <=3){
return '#FBC300';
}else if (value <= 6){
return '#E67716';
}else if (value <= 9){
return '#DA251D';
}else {
return '#733a31';
}
}
},
emphasis: {
label: {
show: true
}
}
},
{% for one in similar_region %}
{
type: 'lines',
coordinateSystem: 'bmap',
zlevel: 2,
data: ods[{{ loop.index0 }}],
//线上面的动态特效
effect: {
show: true,
period: 6,
trailLength: 0.1,
symbolSize: 10,
symbol: planePath
},
tooltip:{
trigger: "item", //提示框
formatter: function (item) {
{#console.log(item);#}
let msg = "<h2>害虫名称:"+item["data"]["insectName"]+"</h2><br>";
msg += "<h3>起始城市:"+item["data"]["fromName"]+"</h3><br>";
msg += "<h3>终止城市:"+item["data"]["toName"]+"</h3><br>";
return msg;
}
},
lineStyle: {
normal: {
color: function (params) {
return random_color();
},
curveness: 0.2
}
}
},
{% endfor %}
];
//实例化
bmapChart.setOption(option);
function random_color(){
return '#'+Math.floor(Math.random()*256).toString(10);
}
</script>
</html>
后台逻辑代码
@app.route("/fbdt")
def fbdt():
# all_address = get_all_insect_address()
# get_all_address()
address_data = get_address_by_sort()
db = pymysql.connect(host="localhost", user="root", password="root", database="reblyhc")
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# try:
# 执行SQL语句
cursor.execute("select * from address")
# 获取所有记录列表
results = cursor.fetchall()
zuobiao = []
all_insect_names = ["杨干象","松突圆蚧","双钩异翅长蠹","美国白蛾","苹果蠹蛾","枣大球蚧","松材线虫病","松疱锈病","冠瘿病","杨树花叶病毒病"
,"落叶松枯梢病","猕猴桃溃疡病","红脂大小蠹","薇甘菊","红棕象甲","青杨脊虎天牛","刺桐姬小蜂","枣实蝇","草履蚧","麻皮蝽","日本脊吉丁","星天牛"
"桑天牛","松墨天牛","柳蓝叶甲","黄刺蛾","褐边绿刺蛾","霜天蛾","杨扇舟蛾","杨小舟蛾","人纹污灯蛾","丝带凤蝶"]
similar_region = []
for row in results:
temp = {}
## 地区名字
temp["name"] = row[1]
temp["lng"] = row[2]
temp["lat"] = row[3]
if row[4] == None:
insect_names = []
for one in address_data:
for i in one["fbdq"]:
if (i in row[1]) or (row[1] in i):
insect_names.append(one["name"])
break
temp["value"] = len(insect_names)
temp["insect_names"] = ','.join(insect_names)
else:
temp["insect_names"] = row[4]
temp["value"] = len(row[4].split(","))
zuobiao.append(temp)
for name in all_insect_names:
temp = []
for region in zuobiao:
if name in region["insect_names"]:
temp.append({"insect_name":name,"name":region["name"],"longitude":region["lng"],"latitude":region["lat"],"isShow":True})
similar_region.append(temp)
db.close()
# return render_template("dt.html",zuobiao=zuobiao)
return render_template("ditu.html",zuobiao=zuobiao,similar_region=similar_region)