86 lines
2.4 KiB
HTML
86 lines
2.4 KiB
HTML
<!DOCTYPE html>
|
||
<html lang="zh-CN">
|
||
<head>
|
||
<meta charset="UTF-8">
|
||
<title>WS实时推送轨迹 - Google Map</title>
|
||
<meta name="viewport" content="width=device-width,initial-scale=1.0">
|
||
<style>
|
||
html, body { height: 100%; margin: 0; padding: 0; }
|
||
#map { width: 100vw; height: 100vh; }
|
||
</style>
|
||
</head>
|
||
<body>
|
||
<div id="map"></div>
|
||
<script>
|
||
// 初始化轨迹
|
||
let path = [];
|
||
let map, marker, polyline;
|
||
|
||
function initMap() {
|
||
map = new google.maps.Map(document.getElementById("map"), {
|
||
zoom: 14,
|
||
center: {lat: 23.0, lng: 121.1}
|
||
});
|
||
|
||
polyline = new google.maps.Polyline({
|
||
path: path,
|
||
geodesic: true,
|
||
strokeColor: "#e53935",
|
||
strokeOpacity: 0.8,
|
||
strokeWeight: 4,
|
||
map: map
|
||
});
|
||
|
||
marker = new google.maps.Marker({
|
||
map: map,
|
||
icon: {
|
||
url: "https://maps.gstatic.com/intl/en_us/mapfiles/markers2/measle_blue.png",
|
||
scaledSize: new google.maps.Size(32, 32)
|
||
}
|
||
});
|
||
}
|
||
|
||
// 连接WebSocket
|
||
function connectWS() {
|
||
// 换成你的ws地址!
|
||
const ws = new WebSocket("ws://127.0.0.1:8099/ws/2746/b9164a7f-f14a-4df0-ab25-e7dae9881796");
|
||
ws.onopen = () => console.log("WebSocket已连接");
|
||
ws.onmessage = (evt) => {
|
||
// 假设后端发过来的是一个点 [lng, lat] 或一组点 [[lng,lat],...]
|
||
let data = JSON.parse(evt.data);
|
||
if(data.cmdType==='update_path'){
|
||
let points = [];
|
||
if (Array.isArray(data[0])) {
|
||
// 一组点
|
||
points = data.map(([lng, lat]) => ({lat, lng}));
|
||
} else {
|
||
// 单个点
|
||
const [lng, lat] = data;
|
||
points = [{lat, lng}];
|
||
}
|
||
// 更新轨迹
|
||
points.forEach(pt => path.push(pt));
|
||
polyline.setPath(path);
|
||
if (path.length === 1) map.setCenter(path[0]);
|
||
marker.setPosition(path[path.length - 1]);
|
||
map.panTo(path[path.length - 1]);
|
||
}
|
||
|
||
};
|
||
ws.onerror = (e) => console.log("WS错误", e);
|
||
ws.onclose = () => {
|
||
console.log("WS断开,3秒后重连");
|
||
setTimeout(connectWS, 3000);
|
||
};
|
||
}
|
||
|
||
window.initMap = initMap;
|
||
window.onload = () => {
|
||
// 保证Google Map加载完后再连ws
|
||
setTimeout(connectWS, 1000);
|
||
};
|
||
</script>
|
||
<!-- 你的 Google Map API KEY -->
|
||
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDIN8ap3znRdSCwW4p3q4ZCpxy3mjBJKNQ&callback=initMap" async defer></script>
|
||
</body>
|
||
</html> |