I am trying to send a coordinate from node.js and socket.io server (index.js) to client.html. In HTML client the coordinate will be read by Leaflet. The problem is, the coordinate variable cannot be read or NaN in client.html
I have tried a simple direct variable initiation and follow the tutorial in Socket.IO pages
Server (index.js)
var e = require('express')();
var http = require('http').Server(e);
var sio = require('socket.io')(http);
http.listen(3000);
e.get('/', function(req, res) {
res.sendFile(__dirname + '/public/client.html');
});
sio.on('connection', function(socket) {
socket.on('ping', function(msg) {
socket.emit('pong', {lat:parseFloat(35+Math.random()),lon:parseFloat(-106+Math.random())});
});
});
Client (client.html)
var socket = io.connect('http://localhost:3000');
socket.on('pong', function(msg) {
console.log("Nilai msg : "+msg);
L.marker([parseFloat(msg.lat),parseFloat(msg.lon)]).addTo(map).bindPopup("("+msg.lat+","+msg.lon+")").openPopup();
var map = L.map('map', {
center: [35.10418, -106.62987],
zoom: 9
});
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png').addTo(map);
map.on("click", function(){
socket.emit('ping', {msg: 'Hello'});
});
I expect the map will show the marker with the corresponding coordinate, but the actual output is Error: Invalid LatLng object: (NaN, NaN)
In socket.io, ping and pong are reserved events and shouldn't be used in your app. What your browser receives on a pong event is not what you expect:
ms (Number) number of ms elapsed since ping packet (i.e.: latency).
and that's why msg.lat and msg.lon are not defined and cannot be parsed.
Change the event names to something else, say fromserver and frombrowser and you should be good to go :
Server side:
io.on('connection', function(socket){
socket.on('frombrowser', function(msg){
var o = {lat:parseFloat(35+Math.random()),lon:parseFloat(-106+Math.random())};
socket.emit('fromserver', o);
});
});
Client side:
socket.on('fromserver', function(msg) {
console.log(msg);
console.log([parseFloat(msg.lat), parseFloat(msg.lon)]);
});
map.on("click", function(){
socket.emit('frombrowser', {msg: 'Hello'});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With