Newer
Older
leaflet / map / web / server.js
const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const cors = require('cors');

const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });

app.use(cors()); // CORSを許可
app.use(express.static('public')); // 静的ファイル提供(HTMLなど)

// 初期位置
let location = { lat: 38.7275, lng: 139.821, timestamp: Date.now() };

// 位置情報を1秒ごとに更新
setInterval(() => {
  location.lat += (Math.random() - 0.5) * 0.001;
  location.lng += (Math.random() - 0.5) * 0.001;
  location.timestamp = Date.now();
}, 1000);

// HTTP APIエンドポイント(ポーリング用)
app.get('/api/position', (req, res) => {
  res.json(location);
});

// WebSocket通信
wss.on('connection', (ws) => {
  console.log('WebSocket connected');

  // 1秒ごとに位置情報を送信
  const interval = setInterval(() => {
    ws.send(JSON.stringify(location));
  }, 1000);

  ws.on('close', () => {
    clearInterval(interval);
  });
});

// サーバー起動
server.listen(3000, () => {
  console.log('Server running at http://localhost:3000');
});