结合WebSocket和Openlayers4实现地图内容的刷新
目录
概述
本文讲述如何结合WebSocket和Openlayers4实现地图内容的实时刷新。
需求概述
- 定时接受推送的数据(tif格式);
- 数据的预处理与加工(png格式);
- 推送到前端并展示。
实现效果
- 列表内容
实现思路
结合WebSocket实现数据加工完后,将结果推送到前端,并在前端展示。在本实例钟,使用了后台的定时刷新机制,模拟数据推送、数据加工这个流程。
实现代码
- pom配置
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
<version>${springmvc.version}</version>
</dependency>
- SpringMVC中socket配置
<!--websocket 配置-->
<bean id="websocket" class="com.lzugis.web.websocket.WebsocketEndPoint"/>
<websocket:handlers allowed-origins="*">
<websocket:mapping path="/websocket" handler="websocket"/>
<websocket:handshake-interceptors>
<bean class="com.lzugis.web.websocket.HandshakeInterceptor"/>
</websocket:handshake-interceptors>
</websocket:handlers>
- WebsocketEndPoint.java
package com.lzugis.web.websocket;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import java.util.Timer;
import java.util.TimerTask;
@RequestMapping("/websocket")
public class WebsocketEndPoint extends TextWebSocketHandler {
private Timer timer;
private static int imgIndex = 0;
private final String[] imgList = {"1.png","2.png","3.png","4.png","5.png","6.png"};
@Override
protected void handleTextMessage(WebSocketSession session,
TextMessage message) throws Exception {
if(!session.isOpen()){
timer.cancel();
return;
}
super.handleTextMessage(session, message);
session.sendMessage(message);
}
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
timer = new Timer(true);
long delay = 0;
OrderTimeTask orderTimeTask = new OrderTimeTask(session);
timer.schedule(orderTimeTask, delay, 5000);// 设定指定的时间time,此处为5s
}
class OrderTimeTask extends TimerTask{
private WebSocketSession session;
public OrderTimeTask(WebSocketSession session){
this.session = session;
}
@Override
public void run() {
try {
String imgPath = imgList[imgIndex];
TextMessage textMessage = new TextMessage(imgPath);
handleMessage(session,textMessage);
imgIndex++;
if(imgIndex==imgList.length)imgIndex=0;
} catch (Exception e){
e.printStackTrace();
}
}
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
System.out.println("Connection Closed!");
}
}
- HandshakeInterceptor.java
package com.lzugis.web.websocket;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;
import java.util.Map;
public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor {
@Override
public boolean beforeHandshake(ServerHttpRequest request,
ServerHttpResponse response, WebSocketHandler wsHandler,
Map<String, Object> attributes) throws Exception {
return super.beforeHandshake(request, response, wsHandler, attributes);
}
@Override
public void afterHandshake(ServerHttpRequest request,
ServerHttpResponse response, WebSocketHandler wsHandler,
Exception ex) {
super.afterHandshake(request, response, wsHandler, ex);
}
}
- 前端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>websocket</title>
<link rel="stylesheet" type="text/css" href="plugin/ol4/ol.css"/>
<style>
body, #map {
border: 0px;
margin: 0px;
padding: 0px;
width: 100%;
height: 100%;
font-size: 13px;
overflow: hidden;
}
#map{
background: #000000;
}
</style>
</head>
<body>
<div id="map"></div>
<script src="plugin/ol4/ol.js"></script>
<script type="text/javascript">
function getTdtSource(lyr) {
var url = "http://t0.tianditu.com/DataServer?T=" + lyr + "&X={x}&Y={y}&L={z}";
return new ol.source.XYZ({
url: url
});
}
var imgExtent = [12602145.594234122,4499928.8932888079,13294552.826968284,5266752.9429073939];
var base_lyr = new ol.layer.Tile({
source: getTdtSource("vec_w")
});
var anno_lyr = new ol.layer.Tile({
source: getTdtSource("cva_w"),
zIndex:1
});
var imgLayer = new ol.layer.Image({
source: null,
opacity:0.6
});
var projection = new ol.proj.Projection({
code: 'EPSG:3857',
units: 'm'
});
var map = new ol.Map({
controls: ol.control.defaults({
attribution: false
}),
target: 'map',
layers: [
base_lyr,
anno_lyr,
imgLayer
],
view: new ol.View({
projection: projection,
center: [12865951.743328119, 4887378.449630305],
zoom: 8
})
});
var websocket = null;
//判断当前浏览器是否支持WebSocket
if ('WebSocket' in window) {
websocket = new WebSocket("ws://localhost:8081/lzugis-web/websocket");
}
else {
alert('当前浏览器 Not support websocket')
}
//连接发生错误的回调方法
websocket.onerror = function () {
console.log("WebSocket连接发生错误");
};
//连接成功建立的回调方法
websocket.onopen = function () {
console.log("WebSocket连接成功");
};
//接收到消息的回调方法
websocket.onmessage = function (event) {
setMessageInnerHTML(event.data);
};
//连接关闭的回调方法
websocket.onclose = function () {
console.log("WebSocket连接关闭");
};
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function () {
closeWebSocket();
};
function setMessageInnerHTML(data) {
var imgSource = new ol.source.ImageStatic({
url: "imgs/"+data,
imageExtent: imgExtent
});
imgLayer.setSource(imgSource);
}
//关闭WebSocket连接
function closeWebSocket() {
websocket.close();
}
</script>
</body>
</html>
技术博客
CSDN:http://blog.csdn.NET/gisshixisheng
博客园:http://www.cnblogs.com/lzugis/
在线教程
http://edu.csdn.Net/course/detail/799
Github
https://github.com/lzugis/
联系方式
类型 | 内容 |
---|---|
1004740957 | |
公众号 | lzugis15 |
niujp08@qq.com | |
webgis群 | 452117357 |
Android群 | 337469080 |
GIS数据可视化群 | 458292378 |
转载自:https://blog.csdn.net/GISShiXiSheng/article/details/79075215