forked from WeronikaSTNK/real-time-map-react
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
51 lines (42 loc) · 1.29 KB
/
Copy pathserver.js
File metadata and controls
51 lines (42 loc) · 1.29 KB
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
const express = require("express");
const cors = require("cors");
const http = require("http");
const socketIo = require("socket.io");
const { range, random } = require("lodash")
const app = express();
app.use(cors());
const server = new http.Server(app);
const io = socketIo(server);
let cars = range(10).map((id) => {
return {
id,
name: `Car ${id}`,
lat: 54.370044 + 0.01 - random(0.2, true),
lng: 18.600549 + 0.01 - random(0.2, true)
}
});
let changeCarsPositionsAndEmitToClients = () => {
console.log('Updating cars positions');
cars = cars.map(oldCar => {
if (random(1, true) < 0.3) {
let updatedCar = {
...oldCar,
lat: oldCar.lat + 0.01 - random(0.02, true),
lng: oldCar.lng + 0.01 - random(0.02, true)
};
io.sockets.clients().emit("carPositionChanged", updatedCar)
return updatedCar;
} else {
return oldCar;
}
})
};
setInterval(changeCarsPositionsAndEmitToClients, 2000);
app.get('/cars', (req, res) => res.send(cars));
io.on("connect", (connection) => {
console.log('emit initial cars', connection)
connection.emit("cars", cars)
});
server.listen(8080, () => {
console.log("Server listening on port 8080")
});