-
Notifications
You must be signed in to change notification settings - Fork 25
/
index.html
285 lines (243 loc) · 9.4 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
<!DOCTYPE html>
<html lang=ru>
<head>
<meta charset="utf-8">
<title>Автобусы на карте</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ==" crossorigin=""/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link href="https://unpkg.com/[email protected]/leaflet-beautify-marker-icon.css" rel="stylesheet">
<style type="text/css">
body {
padding: 0;
margin: 0;
}
html, body, #mapid {
height: 100%;
width: 100vw;
}
</style>
</head>
<body>
<div id="mapid"></div>
<script src="https://unpkg.com/[email protected]/dist/leaflet.js" integrity="sha512-GffPMF3RvMeYyc1LWMHtK8EbPv0iNZ8/oTtHPx9/cc2ILxQ+u905qIwdpULaqDkyBKgOaB57QTMg7ztg8Jm2Og==" crossorigin=""></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet-providers/1.9.0/leaflet-providers.min.js" integrity="sha256-DeMZ/oWlg1cLllekEAI8FfVwhvE2Qsuac66qMoo6vzw=" crossorigin="anonymous"></script>
<script src='https://unpkg.com/[email protected]/Leaflet.Marker.SlideTo.js'></script>
<script src="https://unpkg.com/[email protected]/leaflet-beautify-marker-icon.js"></script>
<script src="https://unpkg.com/[email protected]/Leaflet.Control.Custom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/loglevel/1.6.4/loglevel.min.js" integrity="sha256-ACTlnmNCkOooSKkPCKYbiex8WLE82aeiN+Z9ElZag5Q=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/validate.js/0.13.1/validate.min.js" integrity="sha256-xgP6yiUGsRLSmsC8oW0KrRWiK2ek7cSBznIDMEcdp/U=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
<script type="text/javascript">
const serverUpdateMsgScheme = {
msgType: {presence: true, type: 'string', format: /Buses/},
buses: {presence: true, type: 'array'},
};
const busInfoScheme = {
busId: {presence: true},
lat: {presence: true, type: 'number'},
lng: {presence: true, type: 'number'},
route: {},
};
function validateServerUpdateMsg(jsonData){
const errors = validate(jsonData, serverUpdateMsgScheme);
if (errors){
log.error('Server message format is broken. Check out errors:', errors);
log.info('Following message data was received:', jsonData);
return false;
}
for (let busInfo of jsonData.buses){
const errors = validate(busInfo, busInfoScheme);
if (errors){
log.error('Server message format is broken. Check out bus info errors:', errors);
log.info('Following bus info was received:', busInfo);
return false;
}
}
return true;
}
</script>
<script type="text/javascript">
class WebsocketClosed extends Error {
constructor() {
super('WebsocketClosed');
}
};
async function waitTillSocketOpen(webSocket){
return new Promise((resolve, reject) => {
const onSocketClose = ()=>{
reject(new WebsocketClosed());
webSocket.removeEventListener('open', onWebsocketOpen);
}
const onWebsocketOpen = event => {
resolve();
webSocket.removeEventListener('close', onSocketClose);
}
webSocket.addEventListener('close', onSocketClose);
webSocket.addEventListener('open', onWebsocketOpen);
});
}
async function waitForIncomeMsg(webSocket){
return new Promise((resolve, reject) => {
const onSocketClose = ()=>{
reject(new WebsocketClosed());
webSocket.removeEventListener('message', onMsgReceive);
}
const onMsgReceive = event => {
resolve(event.data);
webSocket.removeEventListener('close', onSocketClose);
}
webSocket.addEventListener('close', onSocketClose);
webSocket.addEventListener('message', onMsgReceive);
});
}
</script>
<script type="text/javascript">
const websocketAddress = localStorage.getItem('websocket') || 'ws://127.0.0.1:8000/ws';
log.info(`Websocket address is ${websocketAddress}`);
const centerOfMoscow = [55.75, 37.6];
var map = L.map('mapid', {
minZoom: 14, // автобусов слишком много, нельзя смотреть всю Москву разом
}).setView(centerOfMoscow, 14);
L.tileLayer.provider('OpenStreetMap.Mapnik').addTo(map);
L.control.custom({
position: 'bottomright',
content: `<input name="address" type="text" value="${websocketAddress}"/>`+
'<button type="button" class="btn btn-info" id="save-btn">Сохранить</button>' +
'<br/>' +
`<label>` +
`<input name="debug" type="checkbox" ${log.getLevel()<=1 && 'checked'}/>` +
'отладка' +
'</label>',
classes: 'btn-group-vertical btn-group-sm',
style: {
padding: '10px',
background: 'rgba(255, 255, 255, 0.7)',
},
events:
{
click: function(event)
{
if (event.target.name == 'debug'){
log.setLevel(event.target.checked && 'debug' || 'warn');
}
if (event.target.id == 'save-btn'){
const newWebsocketAddress = document.getElementsByName("address")[0].value;
localStorage.setItem('websocket', newWebsocketAddress)
document.location.reload();
}
},
}
})
.addTo(map);
const busMarkers = {};
function drawBusMarker(latLng, routeNumber='???', busId='???'){
const icon = L.BeautifyIcon.icon({
isAlphaNumericIcon: true,
text: '' + routeNumber,
iconShape: 'marker',
iconSize: [40, 40],
iconAnchor: [20, 47],
innerIconAnchor: [-5, 7],
borderColor: '#00ABDC',
textColor: '#00ABDC',
});
const marker = L.marker(latLng, { icon: icon })
marker.addTo(map);
marker.bindPopup(`<p>Маршрут №<strong>${routeNumber}</strong>.<br/>Id автобуса ${busId}.</p>`);
return marker;
}
async function sleep(delay){
return new Promise((resolve, reject) => {
setTimeout(resolve, delay);
});
}
function sendBounds(socket, bounds){
const msg = {
'msgType': 'newBounds',
'data': {
'south_lat': bounds._southWest.lat,
'north_lat': bounds._northEast.lat,
'west_lng': bounds._southWest.lng,
'east_lng': bounds._northEast.lng,
},
};
socket.send(JSON.stringify(msg));
log.debug('Send new bounds to the server', msg);
}
function displayBuses(buses){
for (let bus of buses){
const busIdStr = '' + bus.busId;
let marker = busMarkers[busIdStr];
if (!marker){
log.debug(`Place new bus #${busIdStr} on the map. Route ${bus.route}`);
marker = drawBusMarker([bus.lat, bus.lng], bus.route, bus.busId);
busMarkers[busIdStr] = marker;
}
marker.slideTo([bus.lat, bus.lng], {
duration: 500,
});
}
const visibleBusIds = new Set(buses.map(bus => '' + bus.busId));
const drivenAwayBusIds = Object.keys(busMarkers).filter(busId => !visibleBusIds.has(busId));
for (let busId of drivenAwayBusIds){
log.debug(`Bus #${busId} has driven out of the map.`);
busMarkers[busId].remove();
delete busMarkers[busId];
}
}
async function trackBuses(socket){
while (true){
const msgJSON = await waitForIncomeMsg(socket);
try {
var msgData = JSON.parse(msgJSON);
} catch (error) {
log.error(`Expect JSON from server, but receive:`, msgJSON);
continue;
}
if (msgData.msgType == 'Buses'){
if (!validateServerUpdateMsg(msgData)){
return;
}
log.debug('Receive bus positions update from server', msgData);
displayBuses(msgData.buses);
} else {
log.error('Unknown server message received', msgData);
}
}
}
async function listenSocket(){
const socket = new WebSocket(websocketAddress);
await waitTillSocketOpen(socket);
log.info('Websocket connection established');
const sendBoundsToServer = _.debounce(()=>{
const newBounds = map.getBounds();
sendBounds(socket, newBounds);
}, 100)
map.on('zoomend moveend', sendBoundsToServer);
sendBoundsToServer();
try {
await trackBuses(socket);
} finally {
map.off('zoomend moveend', sendBoundsToServer);
}
}
async function listenSocketWithReconnects(){
while (true){
try {
await listenSocket();
} catch (error){
if (error instanceof WebsocketClosed){
log.info('Connection lost. Try to reconnect in 1 sec.')
await sleep(1000);
continue;
}
throw error;
}
}
}
listenSocketWithReconnects();
</script>
</body>
</html>