Leaflet.js, Node.js and Socket.io

3 Sep

UPDATE: Add socket.broadcast.emit(“pong”,{“x”:x,”y”:y}); before the socket.emit() to send location to all users connected. Now you can see everyone else. Will connect this to onLocationFound in Leaflet locate().

I have been using a lot of AJAX recently and really wanted to get in to WebSockets. I installed Node and Socket.io and got to work reading. Finding a super simple example was difficult. Everyone was posting chat servers that I just did not have the patience to read through. Luckily, I found a post by Ynon Perek at http://ynonperek.com/course/node/socket-io.html. I took his echo server and went to work.

I code incrementally. First, I used the code as is. I looked in my Developer Tools window in Chrome and saw that everything was working. The web page was blank and I did not like that. Next, I modified the client by adding a <div id=”result”></div> and changed console.dir(msg) to document.getElementById(“result”).innerHTML=msg.msg (msg is an object with a key msg). Now I could see the results.

I now want to create a Leaflet map that when clicked, a message is sent to the server and it sends back coordinates.

Starting with the client, I added the the references to the JS and CSS files for Leaflet. I added the map div, the connection to the server, created a map and a tile layer. I kept the socket.on(‘connect’) and put in an alert just to make sure the connection worked.

In the original example, as soon as the client connected it kicked off the ping. I created a map.on(“click”) and used it to send the ping. Then on the server, I responded to the ping by getting some random decimals that I added to the Lat and Long range I wanted (35,-106) and sent a “pong” with them.

The client, on receiving a “pong,” created a marker with the coordinates.

Not very useful, but I have a client and server that send messages back and forth over a WebSockets. The end goal is to create a multiple clients that all send messages to the server and can see each other on the map.

Here is the code.

SERVER:

var e = require(‘express’);
var sio = require(‘socket.io’);
var http = require(‘http’);

var app = e();
var server = http.createServer( app );

var io = sio.listen(server);

io.sockets.on(‘connection’, function(socket) {
socket.on(‘ping’, function(msg) {
var x=35+Math.random();
var y=-106+Math.random();
socket.emit(‘pong’, {“x”:x,”y”:y} );
//socket.emit(‘pong’, {“x”:35.10418,”y”:-106.62987} );
});
});

app.get(‘/’, function(req, res) {
res.sendFile(‘client.html’,{root:’/Users/Me/LeafletWebsocket/public/’});
});

server.listen(3000);

 

CLIENT:

<!DOCTYPE html>
<html>
<head>
<title>Leaflet.js Socket.io</title>
<link rel=”stylesheet” href=”http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.css&#8221; />
<style>
html, body, #map {
padding: 0;
margin: 0;
height: 100%;
}

</style>
</head>
<body>
<script src=”http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.js”></script&gt;
<script src=”/socket.io/socket.io.js”></script>
<div id=”message”></div>
<div id=”map”></div>
<script>

var socket = io.connect(‘http://DomainName:3000&#8217;);
socket.on(‘connect’, function() {
alert(“Connected to WebSocket Server”);
});

socket.on(‘pong’, function(msg) {
//document.getElementById(“message”).innerHTML=msg;
L.marker([msg.x,msg.y]).addTo(map).bindPopup(“(“+msg.x+”,”+msg.y+”)”).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’});

});

</script></body></html>

 

PACKAGE.JSON

{
“name”: “SocketServer”,
“version”: “0.0.1”,
“dependencies”: {“express”: “4.8.7”, “socket.io”:”1.0.6″}
}

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: