forked from CartoDB/real-time-map
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdebug.html
496 lines (339 loc) · 13.4 KB
/
debug.html
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Real-Time Map (v. 0.1.0)</title>
<link href="css/style.css" media="screen, projection" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.4.5/leaflet.css" />
<!--[if IE]><link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.4.4/leaflet.ie.css" /><![endif]-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<style type="text/css">
.leaflet-container {
background: #fff;
}
</style>
</head>
<body onload="init();">
<div class="controls">
<a href="#" class="btn toggle_refresh">Stop autorefresh</a>
<a href="#" class="btn refresh">Force refresh</a>
</div>
<div class="message">Map updated</div>
<div class="last-update"></div>
<div id="map"></div>
<script src="http://cdn.leafletjs.com/leaflet-0.4.5/leaflet.js"></script>
<script type="text/javascript" src="js/vendor/wax.leaf.min.js"></script>
<script type="text/javascript" src="js/vendor/cartodb-leaflet-min.js"></script>
<script type="text/javascript" src="js/vendor/cartodb-popup-min.js"></script>
<script type="text/javascript" src="js/vendor/jintervals.js"></script>
<script type="text/javascript" src="js/vendor/jquery.stopwatch.js"></script>
<script type="text/javascript" src="js/vendor/moment.min.js"></script>
<script type="text/javascript">
CONFIG = {
lat: 30.849,
lng: -28.371,
zoom: 3,
maxZoom: 9,
minZoom: 4,
// CartoDB user and main table name
userName: 'viz2',
tableName: 'counties',
// We can observe another table and update the map when it's updated
watchedUserName: 'viz2',
watchedTableName: 'states_results',
style: "#counties { line-width:1; line-color: #ffffff; } \
[status='0'] { polygon-fill: #000000; } \
[status='1'] { polygon-fill: #0000FF; } \
[status='2'] { polygon-fill: #996633; } \
[status='3'] { polygon-fill: #00ffff; } \
[status='4'] { polygon-fill: #00ff00; } \
[status='5'] { polygon-fill: #ff00ff; } \
[status='6'] { polygon-fill: #ff7f00; } \
[status='7'] { polygon-fill: #7f007f; } ",
polygonHoverStyle: { color: "#ff7800", weight: 5, opacity: 0.65, clickable:false },
polygonClickStyle: { color: "red", weight: 5, opacity: 0.65, clickable:false }
};
autolock = false;
stop_refresh = false;
lock_refresh = false;
refresh_interval = 3000;
window.stop_refresh = stop_refresh;
window.lock_refresh = lock_refresh;
window.refresh_interval = refresh_interval;
window.refresh = refresh;
var
hoverData = null,
timeID = null,
request = null,
timer = null,
lastEpoch = null;
var
popup = null,
map = null;
var // layers
layer = null,
geojsonLayer = new L.GeoJSON(null),
clickLayer = new L.GeoJSON(null);
var oldIE = ($.browser.msie && $.browser.version < 9) ? true : false;
// Request animation frame
window.cancelRequestAnimFrame = ( function() {
return window.cancelAnimationFrame ||
window.webkitCancelRequestAnimationFrame ||
window.mozCancelRequestAnimationFrame ||
window.oCancelRequestAnimationFrame ||
window.msCancelRequestAnimationFrame ||
function( callback ){
window.clearTimeout(timeID);
};
})();
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function( callback ){
timeID = window.setTimeout(callback, 1000 / 60);
};
})();
// Stop watch methods
function setupStopWatch() {
$('.last-update').stopwatch({format: 'Last update: <strong>{Minutes} and {seconds} ago</strong>'});
}
function startStopWatch() {
$(".last-update").stopwatch('start');
}
function resetStopWatch() {
$(".last-update").stopwatch('reset');
}
function showMessage(message, hide) {
$(".message").html(message);
$(".message").animate({ opacity: 1, top: 0 }, { duration: 250, complete: function() {
if (hide) {
setTimeout(function() {
$(".message").animate({ opacity: 0, top: "-40px" }, 250);
}, 3000);
}
}});
}
// Adds a polygon in the area where the user clicked
function addClickPolygon(data) {
if (!hoverData) return;
map.removeLayer(clickLayer);
var polygon = {
type: "Feature",
geometry: {
type: "Polygon",
coordinates: [hoverData[data.cartodb_id]]
}
};
clickLayer = new L.GeoJSON(polygon, { style: CONFIG.polygonClickStyle });
map.addLayer(clickLayer);
clickLayer.cartodb_id = data.cartodb_id;
}
// Adds a hihglighted polygon
function highlightPolygon(data) {
if (!hoverData) return;
// Show the hover polygon if it is a different feature
map.removeLayer(geojsonLayer);
var polygon = {
type: "Feature",
geometry: {
type: "Polygon",
coordinates: [hoverData[data.cartodb_id]]
}
};
geojsonLayer = new L.GeoJSON(polygon, { style: CONFIG.polygonHoverStyle });
map.addLayer(geojsonLayer);
geojsonLayer.cartodb_id = data.cartodb_id;
}
function onFeatureClick(e, latlng, pos, data) {
if (typeof( window.event ) != "undefined" ) { // IE
e.cancelBubble=true;
} else { // Rest
e.preventDefault();
e.stopPropagation();
}
// Set popup content
popup.setContent(data);
// Set position
popup.setLatLng(latlng);
// Show the popup
map.openPopup(popup);
addClickPolygon(data);
}
function onFeatureOut() {
if (!hoverData) return;
document.body.style.cursor = "default";
geojsonLayer.cartodb_id = null;
geojsonLayer.off("featureparse");
map.removeLayer(geojsonLayer)
}
function onFeatureHover(e, latlng, pos, data) {
document.body.style.cursor = "pointer";
highlightPolygon(data);
}
function createLayer(version, opacity) {
var query = "SELECT st_name, st_usps, counties.the_geom_webmercator, counties.cartodb_id, states_results.gov_result as status, counties.fips as thecode, counties.st_usps as usps FROM counties, states_results WHERE states_results.usps = counties.st_usps AND version="+version;
return new L.CartoDBLayer({
map: map,
tiler_domain: "{s}.viz2.cartodb.com",
subdomains: "abcd",
//user_name: "viz2", // <- if you don't use a CDN put your username here
table_name: CONFIG.tableName,
tile_style: CONFIG.style,
opacity: opacity,
query: query,
extra_params: {
cache_buster: version,
cache_policy: 'persist'
},
interactivity: "cartodb_id, status, st_usps",
featureOver: onFeatureHover,
featureOut: onFeatureOut,
featureClick: onFeatureClick,
debug: true
});
}
// Fade in and switch the layers
function fadeIn(lyr) {
var
deleted = false,
opacity = 0;
(function animloop(){
request = requestAnimFrame(animloop);
lyr.setOpacity(opacity);
opacity += .05;
if (!deleted && opacity >= 1 ) {
opacity = 0;
deleted = true;
resetStopWatch();
cancelRequestAnimFrame(request);
// Switch layers
map.removeLayer(layer);
layer = lyr;
map.invalidateSize(false);
setTimeout(function() {
console.log("There are " + $(".leaflet-layer").length + " layer/s");
}, 1000);
}
})();
}
// When the new layer is fully loaded, we show it gradually.
// Then we remove the old layer.
function onLayerLoaded(layerNew) {
layerNew.off("load", null, layerNew); // unbind the load event
showMessage("Map updated", true);
lock_refresh = false;
if (oldIE) { // since IE<9 doesn't support opacity, we just remove the layer
map.removeLayer(layer);
layer = layerNew; // layer switch
map.invalidateSize(false);
} else {
fadeIn(layerNew);
}
}
function refresh(force) {
if ( autolock || lock_refresh || (stop_refresh && force != true) ) return;
// We ping this URL every 3000 ms (or the number defined in CONFIG.refreshInterval) and if the table was updated we create a new layer.
var url = "http://" + CONFIG.watchedUserName + ".cartodb.com/api/v2/sql?q=" + escape("SELECT max(version) as epoch_updated FROM " + CONFIG.watchedTableName);
$.ajax({ url: url, cache: true, jsonpCallback: "callback", dataType: "jsonp", success: function(data) {
try {
if (!data.rows) {
data = JSON.parse(data);
}
} catch(e) {
console.log("Error", e);
return;
}
var epoch = data.rows[0].epoch_updated;
if (epoch > lastEpoch) { // Update the map
if (!layer) { // create layer
layer = createLayer(epoch, 1);
map.addLayer(layer, false);
startStopWatch();
} else { // update layer
showMessage("New data coming…", false);
lock_refresh = true;
var opacity = (oldIE) ? 1 : 0; // since IE<9 versions don't support opacity we just create a visible layer
var layerNew = createLayer(epoch, opacity);
map.addLayer(layerNew, false);
layerNew.on("load", function() {
onLayerLoaded(this);
});
}
lastEpoch = epoch;
}
}});
if (!timer) { // creates the timer
timer = setInterval(refresh, refresh_interval);
}
}
// To maximize the feature hover/out speed we load the geometries of the counties in a hash
function getHoverData() {
var url = "http://com.cartodb.uselections.s3.amazonaws.com/hover_geoms/cty0921md_01.js";
$.ajax({ url: url, jsonpCallback: "callback", dataType: "jsonp", success: function(data) {
hoverData = data;
}});
}
function stateChanged(){
console.log(document.webkitVisibilityState);
console.log(document.visibilityState);
if (document.hidden || document.webkitHidden || document.msHidden || document.mozHidden){
//new tab or window minimized
timer = new Date().getTime();
autolock = true;
} else {
console.log('You were away for ' + (new Date().getTime()-timer)/1000+ ' seconds.')
autolock = false;
}
}
function init() {
document.addEventListener("mozvisibilitychange", stateChanged, false);
document.addEventListener("visibilitychange", stateChanged, false);
document.addEventListener("webkitvisibilitychange", stateChanged, false);
document.addEventListener("msvisibilitychange", stateChanged, false);
$(".toggle_refresh").on("click", function(e) {
e.preventDefault();
e.stopPropagation();
if (autolock && stop_refresh == false) return;
stop_refresh = !stop_refresh;
if (stop_refresh) {
$(this).html("Start autorefresh");
$(this).parent().addClass("stopped");
} else {
$(this).html("");
$(this).html("Stop autorefresh");
$(this).parent().removeClass("stopped");
}
});
$(".refresh").on("click", function(e) {
e.preventDefault();
e.stopPropagation();
refresh(true);
console.log("refreshing");
});
setupStopWatch();
// Initialize the popup
popup = new L.CartoDBPopup();
// Get the counties' geometries
getHoverData();
// Set the map options
var mapOptions = {
center: new L.LatLng(CONFIG.lat, CONFIG.lng),
zoom: CONFIG.zoom,
maxZoom: CONFIG.maxZoom,
minZoom: CONFIG.minZoom,
zoomAnimation: true,
fadeAnimation: true
};
map = new L.Map('map', mapOptions);
map.on("popupclose", function() {
map.removeLayer(clickLayer);
});
refresh(); // Go!
}
</script>
<a href="https://github.com/cartodb/real-time-map"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png" alt="Fork me on GitHub"></a>
</body>
</html>