HTML 页面
<!DOCTYPE html>
<html>
<head>
<title>Accessible Map</title>
<link rel="stylesheet" href="https://openlayers.org/en/v3.20.1/css/ol.css" type="text/css">
<!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
<script
src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL">
</script>
<script src="https://openlayers.org/en/v3.20.1/build/ol.js"></script>
<style>
a.skiplink {
position: absolute;
clip: rect(1px, 1px, 1px, 1px);
padding: 0;
border: 0;
height: 1px;
width: 1px;
overflow: hidden;
}
a.skiplink:focus {
clip: auto;
height: auto;
width: auto;
background-color: #fff;
padding: 0.3em;
}
#map:focus {
outline: #4A74A8 solid 0.15em;
}
</style>
</head>
<body>
<div id="map" class="map" tabindex="0"></div>
<script>
var longitude = 106.6280289;
var latitude = 26.6220112;
var socket = null;
window.load = initWebSocket();
function initWebSocket() {
//初始化weosocket
if (typeof(WebSocket) == "undefined") {
console.log("您的浏览器不支持WebSocket");
} else {
console.log("您的浏览器支持WebSocket");
var ip = '127.0.0.1'
var port = 10086
var userId = 1;
//实现化WebSocket对象,指定要连接的服务器地址与端口 建立连接
var socketUrl = "ws://" + ip + ":" + port + "/webSocket/" + userId;
console.log(socketUrl);
if (socket != null) {
socket.close();
socket = null;
}
socket = new WebSocket(socketUrl);
//打开事件
socket.onopen = function() {
console.log("websocket已打开");
//socket.send("这是来自客户端的消息" + location.href + new Date());
};
/*
//获得消息事件
socket.onmessage = function(msg) {
var serverMsg = "收到服务端信息:" + msg.data;
console.log(serverMsg);
//发现消息进入 开始处理前端触发逻辑
};
*/
//关闭事件
socket.onclose = function() {
console.log("websocket已关闭");
};
//发生了错误事件
socket.onerror = function() {
console.log("websocket发生了错误");
}
}
}
//把经纬度发给后端
function sendMessage() {
getMessage();
if (typeof(WebSocket) == "undefined") {
console.log("您的浏览器不支持WebSocket");
} else {
var msg = '{' + "longitude:" + longitude + ",latitude:" + latitude + '}'
socket.send(msg);
}
}
// 模拟后台数据
var trackData = [
{
"lon":longitude,
"lat":latitude
},
]
var features = []
var map = new ol.Map({
target: 'map',
view: new ol.View({
center: ol.proj.fromLonLat([longitude, latitude]),
zoom: 20
}),
layers:[
]
})
// 底图
var tileLayer = new ol.layer.Tile({
source: new ol.source.OSM()
});
//接收后端传过来的经纬度
function getMessage() {
socket.onmessage = function(msg) {
var serverMsg = "收到服务端信息:" + msg.data;
var data = JSON.parse(msg.data);
let lonLat = {};
lonLat.lon = data[0];
lonLat.lat = data[1];
trackData = lonLat;
var coordinate = ol.proj.transform([lonLat.lon,lonLat.lat],'EPSG:4326','EPSG:3857')
features[0] = new ol.Feature({
geometry: new ol.geom.Point(coordinate)
})
// 点图层
var addFeature = new ol.layer.Vector({
source: new ol.source.Vector({
features: features
}),
style: new ol.style.Style({
image: new ol.style.Circle({
radius: 5,
stroke: new ol.style.Stroke({
color:'#fff'
}),
fill: new ol.style.Fill({
color:'#f00'
})
})
})
})
map.addLayer(tileLayer)
map.addLayer(addFeature)
}
//发现消息进入 开始处理前端触发逻辑
};
//每隔1秒钟发送一次
var int = self.setInterval("sendMessage()", 200);
/*
for(var i=0;i<trackData.length;i++){
// 将点转换成地图识别的格式
var coordinate = ol.proj.transform([trackData[i].lon,trackData[i].lat],'EPSG:4326','EPSG:3857')
features[i] = new ol.Feature({
geometry: new ol.geom.Point(coordinate)
})
}
*/
</script>
</body>
</html>
pom.xml
<!-- websocket -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<version>2.2.7.RELEASE</version><!--$NO-MVN-MAN-VER$-->
</dependency>
后端Java
WebSocketConfig.java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* @version 创建时间:2020年10月13日 上午9:59:27
*/
@Configuration
public class WebSocketConfig {
/**
* ServerEndpointExporter 作用
*
* 这个Bean会自动注册使用@ServerEndpoint注解声明的websocket endpoint
*
* @return
*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
WebSocketServer.java
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import org.apache.commons.collections4.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/**
* @version 创建时间:2020年10月13日 上午10:01:33
*/
@ServerEndpoint("/webSocket/{sid}")
@Component
public class WebSocketServer {
//记录当前连接数
private static AtomicInteger onlineNum = new AtomicInteger();
//concurrent包的线程安全Set,用来存放每个客户端对应的WebSocketServer对象。
private static ConcurrentHashMap<String, Session> sessionPlools = new ConcurrentHashMap();
//发送消息
public void sendMessage(Session session, String message) throws IOException {
if(session != null) {
synchronized (session) {
session.getBasicRemote().sendText(message);
}
}
}
//给指定用户发送信息
public void sendInfo(String userName, String message) {
Session session = sessionPlools.get(userName);
try {
sendMessage(session, message);
} catch (IOException e) {
e.printStackTrace();
}
}
//建立连接调用
@OnOpen
public void onOpen(Session session, @PathParam(value = "sid")String userName){
sessionPlools.put(userName, session);
addOnlineCount();
System.out.println(userName + "加入webSocket!当前人数为" + onlineNum);
/*
try {
sendMessage(session, "欢迎" + userName + "加入连接!");
} catch (IOException e) {
e.printStackTrace();
}
*/
}
//关闭连接
public void onClose(@PathParam("sid")String userName) {
sessionPlools.remove(userName);
subOnlineCount();
System.out.println(userName + "断开webSocket连接!当前人数为" + onlineNum);
}
//收到客户端信息
@OnMessage
public void onMessage(String message){
//{longitude:106.6280289,latitude:26.6220112}
//message = "客户端:\' "+ message +"\'已收到!";
Map<String, String> map = getLogitude(message);
message = "["+map.get("longitude")+","+map.get("latitude")+"]";
System.out.println(message);
for (Session session : sessionPlools.values()) {
try {
sendMessage(session, message);
} catch (IOException e) {
e.printStackTrace();
continue;
}
}
}
//错误时调用
@OnError
public void onError(Session session, Throwable throwable) {
System.out.println("发生错误!");
throwable.printStackTrace();
}
public static void addOnlineCount() {
onlineNum.incrementAndGet();
}
public static void subOnlineCount() {
onlineNum.decrementAndGet();
}
/**
* 获取到经纬度
* @param message 传过来的消息
* @return
*/
public Map<String, String> getLogitude(String message) {
int i = (int)(Math.random() * 10)+ 1;
Map<String, String> map = new HashedMap<String, String>();
String[] source = message.substring(1, message.length()-1).split(",");
String longitude = source[0].split(":")[1];
String latitude = source[1].split(":")[1];
double x = 0.001D;
double random = Math.random();
x = plus(x, random);
double longitude1 = 0;
double latitude1 = 0;
if(i % 2 == 0) {
longitude1 = mul(x, Double.valueOf(longitude));
latitude1 = mul(x, Double.valueOf(latitude));
}else if(i % 3 ==0) {
longitude1 = subtract( Double.valueOf(longitude), x);
latitude1 = subtract(Double.valueOf(latitude), x);
}else if(i % 5 == 0) {
longitude1 = mul( Double.valueOf(longitude), x);
latitude1 = subtract(Double.valueOf(latitude), x);
}else {
longitude1 = subtract( Double.valueOf(longitude), x);
latitude1 = mul(Double.valueOf(latitude), x);
}
map.put("longitude", String.valueOf(longitude1));
map.put("latitude", String.valueOf(latitude1));
return map;
}
/**
* 两个double类型相加
* @param v1 参数一
* @param v2 参数二
* @return
*/
public double mul(double v1,double v2){
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.add(b2).doubleValue();
}
/**
* 两个double类型相乘
* @param v1 参数一
* @param v2 参数二
* @return
*/
public double plus(double v1,double v2){
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.multiply(b2).doubleValue();
}
/**
* 两个double类型相减
* @param v1 参数一
* @param v2 参数二
* @return
*/
public double subtract(double v1,double v2){
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.subtract(b2).doubleValue();
}
}