-
Notifications
You must be signed in to change notification settings - Fork 2
/
websockets.js
306 lines (233 loc) · 7.94 KB
/
websockets.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
// HTML5 WEBSOCKET
// Full duplex, bi-directional transport
// Show Inspector - Frames debug in Chrome Dev Tools
// Simple API
var ws = new WebSocket("ws://html5hacks.com/socket");
ws.onopen = function () {
ws.send("Hello World"); // send messsage to the server
console.log("Message sent!");
};
ws.onmessage = function (evt) {
var received_msg = evt.data;
console.log("Message received = "+received_msg);
};
ws.onclose = function () {
// websocket is closed.
console.log("Connection is closed...");
};
// Socket.io
// CONNECTION
socket = io.connect('/');
// PUBLISHERS - .emit()
// Called on positionSuccess() and in updateMarker()
'send:coords'
// SUBSCRIBERS - .on()
// NerdType Counts
'count'
'count:developers'
'count:designers'
// Set the Markers of other Users
'load:coords'
// SSJS - Node.js Socket.io
socket.on('send:coords', function (data) {
socket.broadcast.emit('load:coords', data);
});
///////////////////////////////////////////////////////////////////////////////////////////////////////////
$(function() {
var initData = JSON.parse($('#data-record').html());
var username = initData.username;
// generate unique user id
var userId = Math.random().toString(16).substring(2,15);
// Connect to socket server
var socket = io.connect('/');
// MAP SETUP
var map;
var info = $('#infobox');
var doc = $(document);
// custom marker's icon styles
var tinyIcon = L.Icon.extend({
options: {
shadowUrl: '../vendor/leaflet/assets/marker-shadow.png',
iconSize: [25, 39],
iconAnchor: [12, 36],
shadowSize: [41, 41],
shadowAnchor: [12, 38],
popupAnchor: [0, -30]
}
});
var redIcon = new tinyIcon({ iconUrl: '../vendor/leaflet/assets/marker-red.png' });
var orangeIcon = new tinyIcon({ iconUrl: '../vendor/leaflet/assets/marker-orange.png' });
var blueIcon = new tinyIcon({ iconUrl: '../vendor/leaflet/assets/marker-blue.png' });
var greenIcon = new tinyIcon({ iconUrl: '../vendor/leaflet/assets/marker-green.png' });
var yellowIcon = new tinyIcon({ iconUrl: '../vendor/leaflet/assets/marker-yellow.png' });
var purpleIcon = new tinyIcon({ iconUrl: '../vendor/leaflet/assets/marker-purple.png' });
var sentData = {}
var connects = {};
var active = false;
// Marker Clusters
markers = new L.MarkerClusterGroup();
// END MAP SETUP
socket.on('count', function (data) {
$(".count").text(data.number);
});
socket.on('count:developers', function (data) {
$(".developers-count").text(data.number);
});
socket.on('count:designers', function (data) {
$(".designers-count").text(data.number);
});
// Set up the Markers of other users
socket.on('load:coords', function(data) {
console.log('load:coords');
console.log("New User in Connects obj: " , connects)
// check if the user is new
// connects holds onto all user ids
// set the marker if that instance with unique id is not present in connects object.
// unique id and coords were created on page load
// BUG: so refreshing the page creates a new id and broadcasts to other users
// Need to check for inactivity and then remove them
if (!(data.id in connects)) {
setMarker(data);
}
connects[data.id] = data;
connects[data.id].updated = $.now(); // shorthand for (new Date).getTime()
});
// check whether browser supports geolocation api
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(positionSuccess, positionError, { enableHighAccuracy: true });
} else {
$('.map').text('Your browser is out of fashion, there\'s no geolocation!');
}
function positionSuccess(position) {
console.log('positionSuccess');
var lat = position.coords.latitude;
var lng = position.coords.longitude;
var acr = position.coords.accuracy;
// Set up Map
// mark user's position
userMarker = L.marker([lat, lng], {
icon: orangeIcon
});
map = L.map('map', {
zoomControl: false,
attributionControl: false
});
map.setView(new L.LatLng(lat, lng), 14)
// leaflet API key tiler
L.tileLayer('http://{s}.tile.cloudmade.com/BC9A493B41014CAABB98F0471D759707/997/256/{z}/{x}/{y}.png', { maxZoom: 18, detectRetina: true }).addTo(map);
userMarker.addTo(map);
userMarker.bindPopup(
'<p>' + initData.nerdtype + ': '
+ initData.username + '</p>'
).openPopup();
// NERDTYPE LEGEND
var legend = L.control({position: 'topleft'});
legend.onAdd = function (map) {
var div = L.DomUtil.create('div', 'info legend'),
types = ['You', 'Developers', 'Designers', 'Managers', 'Gamers', 'Makers'],
colors = ['orange', 'blue', 'green', 'yellow', 'purple', 'red']
labels = ['me', 'developer', 'designer', 'business-geek'];
// loop through our density intervals and generate a label with a colored square for each interval
for (var i = 0; i < types.length; i++) {
div.innerHTML +=
"<img style='padding: 2px 0' src='../vendor/leaflet/assets/marker-" + colors[i] + ".png'> " +
types[i] + (types[i] ? '<br>' : '');
}
return div;
};
legend.addTo(map);
// END SET UP MAP
sentData = {
id: userId,
nerdtype: initData.nerdtype,
username: initData.username,
active: active,
coords: [{
lat: lat,
lng: lng,
acr: acr
}]
}
// Send Data to all connnected clients
socket.emit('send:coords', sentData);
}
function updateMarker( marker, lat, lng, label ){
console.log('updating marker location')
sentData = {
id: userId,
nerdtype: initData.nerdtype,
username: initData.username,
active: active,
coords: [{
lat: lat,
lng: lng
}]
}
var latlng = new L.LatLng(lat, lng);
userMarker.setLatLng(latlng);
// Send Data to all connnected clients
socket.emit('send:coords', sentData);
}
var positionTimer = navigator.geolocation.watchPosition(
function(position){
console.log( "Newer Position Found: " + position.coords.latitude + ", " + position.coords.longitude);
//alert( "Newer Position Found: " + position.coords.latitude + ", " + position.coords.longitude);
updateMarker(
userMarker,
position.coords.latitude,
position.coords.longitude,
"Updated / Accurate Position"
);
}
);
function setMarker(data) {
nerdsPoints = [];
nerdsPoints.push(data);
for (var i = 0; i < nerdsPoints.length; i++) {
var lat = nerdsPoints[i].coords[0].lat;
var lng = nerdsPoints[i].coords[0].lng;
var nerdtype = nerdsPoints[i].nerdtype;
var username = nerdsPoints[i].username;
var title = nerdtype + ", " + username;
switch(nerdtype){
case 'developer':
var icon = blueIcon;
break;
case 'designer':
var icon = greenIcon;
break;
case 'manager':
var icon = yellowIcon;
break;
case 'gamer':
var icon = purpleIcon;
break;
case 'maker':
var icon = redIcon;
break;
default:
var icon = purpleIcon;
};
var marker = new L.Marker(
new L.LatLng(lat, lng),
{ title: title, icon: icon }
);
marker.bindPopup(title);
markers.addLayer(marker);
}
map.addLayer(markers);
markers[data.id] = marker;
};
function positionError(error) {
var errors = {
1: 'Authorization fails', // permission denied
2: 'Can\'t detect your location', //position unavailable
3: 'Connection timeout' // timeout
};
showError('Error:' + errors[error.code]);
};
function showError(msg) {
info.addClass('error').text(msg);
doc.click(function() { info.removeClass('error') });
};
});