Ad

Object Not Sent In Socket.io

- 1 answer

I have the following code

$locationButton.onclick = () => {
    if(!navigator.geolocation) { return alert('method unavailable'); }
    $locationButton.setAttribute('disabled', 'disabled');
    navigator.geolocation.getCurrentPosition((position) => {
        console.log(position)
        $locationButton.removeAttribute('disabled');
        socket.emit('USER:SEND_LOCATION', position, (response) => {
            console.log(response)
        });
    })
}

and on server

socket.on('USER:SEND_LOCATION', (position: any, callback: Function) => {
    console.log(position)
    const timestamp = Date.now();
    socket.broadcast.emit('SERVER:NEW_LOCATION', {position, timestamp, user: 'Me'});
    callback({position, timestamp, user: 'Me'});
})

The problem I have is, in client, there is a position object on the first console.log, then I try send it do the server, and the server always get only an empty object instead '{}'

I tried json.strigify, but I sill get a '{}'

Ad

Answer

The issue with the position object/result that you get from calling navigator.geolocation.getCurrentPosition is that it's properties are not enumerable, meaning that you can't easily "stringify" the object and pass it along with your socket.emit call, which is why you're getting an empty object as a result.

Although you can write a function that will extract these properties for you, you could do the following:

navigator.geolocation.getCurrentPosition((position) => {
  const payload = {
    coords: {
      accuracy: position.coords.accuracy,
      altitude: position.coords.altitude,
      altitudeAccuracy: position.coords.altitudeAccuracy,
      heading: position.coords.heading,
      latitude: position.coords.latitude,
      longitude: position.coords.longitude,
      speed: position.coords.speed
    },
    timestamp: position.timestamp
  }
  socket.emit('USER:SEND_LOCATION', JSON.stringify(payload))
})

Then, on your server side, you can do the following:

socket.on('USER:SEND_LOCATION', (position, callback) => {
  const data = JSON.parse(position)

  console.log(data) // { coords: {...}, timestamp: ... }
})

If you'd like a little cleaner solution, have a look at this function that will take the position object and turn it into an object that can be easily "stringified":

Ad
source: stackoverflow.com
Ad