将插座彼此分开,

时间:2019-02-23 19:17:44

标签: javascript node.js sockets websocket socket.io

我正在尝试使用Web套接字创建实时跟踪系统,我能够获取用户的坐标并将标记放置在地图上,但是我不希望一个用户看到其他用户的标记。我大致知道我需要使用io.to()的确切信息,但没有确切地知道如何使用它。我的另一个问题是,当我关闭HTML页面时,在socket.on('disconnect')方法中没有得到断开连接的消息。有人可以帮忙吗?

客户端JS -Viewer.js

let map;
let markers = new Map();

document.addEventListener('DOMContentLoaded', () => {
  const socket = io('/');

  const positionOptions = {
    enableHighAccuracy: true,
    maximumAge: 0
  };

  setInterval(() => {
    navigator.geolocation.getCurrentPosition(pos => {
      console.log("came inside set interval first one");
      const { latitude: lat, longitude: lng } = pos.coords
      socket.emit('updateLocation', { lat, lng })
    }, err => {
      console.error(err)
    }, positionOptions)
  }, 2000);

  socket.on('locationsUpdate', locations => {
    console.log(locations);
    // myMap.forEach(function(value, key) {
    //   console.log(key + ' = ' + value);
    // });
    markers.forEach((marker,id) => {
      marker.setMap(null)
      markers.delete(id)
    });

    locations.forEach(([id, position]) => {
      if (position.lat && position.lng) {
        var image = 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png';
        const marker = new google.maps.Marker({
          position:position,
          map:map,
          icon:image
        })
        markers.set(id, marker)
        console.log(markers);
      }
    })
  });

  setInterval(() => {
    console.log("came inside setInterval, calling requestLocations");
    socket.emit('requestLocations')
  }, 2000);
});
function initMap() {
  console.log("came inside init map");
  navigator.geolocation.getCurrentPosition(pos => {
    const { latitude: lat, longitude: lng } = pos.coords
    map = new google.maps.Map(document.getElementById('map'), {
      center: { lat, lng },
      zoom: 20
    })

  }, err => {
    console.error(err)
  })
}

在服务器端,下面是代码

const http = require('http')
const path = require('path')
const express = require('express')
const bodyParser = require('body-parser')
const socketIo = require('socket.io')

const app = express()
const server = http.createServer(app)
const io = socketIo(server)

const locationMap = new Map()
app.use(express.static(path.join(__dirname, 'public')))

app.get('/', (req, res) => {
  res.send('Hello');
})

io.on('connection', socket => {

  socket.on('updateLocation', pos => {
    locationMap.set(socket.id, pos)
  })

  socket.on('requestLocations', () => {
    console.log(locationMap);
    console.log(Array.from(locationMap));
    socket.emit('locationsUpdate', Array.from(locationMap))
  })

  socket.on('disconnect', () => {
    console.log("disconnected");
    locationMap.delete(socket.id)
  })
})

server.listen(3000, err => {
  if (err) {
    throw err
  }

  console.log('server started on port 3000')
})

0 个答案:

没有答案