This repository has been archived by the owner on Aug 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathshowTrail.html
674 lines (573 loc) · 24.8 KB
/
showTrail.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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
<!DOCTYPE html>
<html lang="en-NZ">
<head>
<title>Sensibel ~ Journey browser</title>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" />
<script src="http://code.jquery.com/jquery-2.2.0.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script> <!-- FIXME: only need listview from JQM, can't assemble a custom package -->
<script src="https://cdn.rawgit.com/agschwender/jquery.formatDateTime/master/dist/jquery.formatDateTime.min.js"></script> <!-- canonical source: https://github.com/agschwender/jquery.formatDateTime/raw/master/dist/jquery.formatDateTime.min.js -->
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>
<script src="https://cdn.rawgit.com/makinacorpus/Leaflet.GeometryUtil/master/src/leaflet.geometryutil.js"></script>
<script src="https://cdn.rawgit.com/makinacorpus/Leaflet.AlmostOver/gh-pages/src/leaflet.almostover.js"></script>
<script src="https://npmcdn.com/@turf/[email protected]/turf.min.js"></script>
<!-- <script src="lib/spectrum.js"></script> -->
<script src="config.js"></script>
<!-- <link rel="stylesheet" type="text/css" href="ui/css/spectrum.css" /> -->
<link href="https://fonts.googleapis.com/css?family=Raleway:400,uni,b,bi" rel="stylesheet" />
<link rel="stylesheet" type="text/css" href="ui/css/basic.css" />
<link rel="stylesheet" type="text/css" href="ui/css/resets.css" />
<script type="text/javascript">
var map;
var _VERSION = '0.2.20';
var UNKNOWN_CYCLIST = '[the unknown cyclist]';
var UNKNOWN_TIME = '[not recorded]';
var BUTTON_VALUE_GOOD = '01';
var BUTTON_VALUE_BAD = '02';
var categories = [ // FIXME: obviously not a continuing goer
'Infrastructure',
'Environmental',
'Wayfinding',
'Social',
'Safety',
'Near miss',
'Traffic',
'Bike mechanics',
];
$(document).ready(function() {
$('h1').after('<span class="meta version">v' + _VERSION + ' (<a href="showTrail.html">latest</a>)</span>');
if ( map === undefined ) {
map = L.map('viz-canvas').setView([-36.85, 174.76], 13);
var baseMaps = {
'Dark Matter': config.layer.CartoDB_DarkMatter.tiles,
'OSM Carto': config.layer.osm.tiles,
'Thunderforest OpenCycleMap': config.layer.Thunderforest_OpenCycleMap.tiles,
}
baseMaps['Dark Matter'].addTo(map);
L.control.layers(baseMaps).addTo(map);
}
// console.log(map);
journeys = new journeyRecords(config.AWS_S3);
loadedRecords = {}; // NB. choice is to keep records since they are being loaded below anyway, though that is not optimal or necessarily going to stay the case ..
// The other option would be to load the track file as required only
$('#journeys').listview();
// $('#journeys').append($('<h2>Heading TODO</h2>')); // FIXME: this gets prepended to, so something more like .after() is required, or the sequence to be looked at
journeys.list( function(contents) {
itemNames = [];
$.each(contents, function(index, item) {
var itemName = $(item).find('Key').text();
itemNames.push(itemName);
itemRecord = new journeyRecord(config.AWS_S3);
itemRecord.load(itemName, function(record) {
record = $.extend(new journeyRecord(), record); // essentially casting record as a journeyRecord because console says it doesn't have the methods - don't really understand why this is necessary
if (record.metadata) {
var itemId = itemName.replace('-','.'); // wish I'd explained myself here
var itemReference = itemName.replace(/\.json$/, '');
/* console.log( (Math.floor(Math.random() * (34 - 170 + 1)) + 170).toString(16) ); */ // experiment with random track colours
var rider = record.metadata.hasOwnProperty('rider') ? record.metadata.rider : UNKNOWN_CYCLIST;
var duration = ( record.metadata.hasOwnProperty('started') && record.metadata.hasOwnProperty('ended')
? function(start, finish){
var bits = millisecondsToComponents(new Date(finish) - new Date(start));
// FIXME: something about $().after() I don't get - jQ won't return the seconds unbolded here
// return $('<strong/>').text(bits.hours + ':' + bits.mins).after(':' + bits.secs);
return bits.hours + ':' + bits.mins + ':' + bits.secs;
}(record.metadata.started, record.metadata.ended)
: '[not recorded]'
);
var $heading = $('<h3/>')
// .attr('title', itemReference) // this is invaluable at times if debugging based on file names
.append($('<label/>')
.attr('for', itemId)
.text(rider)
// .click(function() { console.log($('#' + itemId)); $('#' + itemId).prop("checked", !$('#' + itemId).prop("checked")); }) record.metadata.name
);
var $content = $('<p/>')
.attr('class','journey-summary')
.append( function() {
var $span = $('<span/>')
.attr('class', 'meta date')
.text( record.metadata.hasOwnProperty('started') ? $.formatDateTime('MM dS, hh:ii', new Date(record.metadata.started)) : UNKNOWN_TIME ) // record.GJ.... TODO
;
if(record.metadata.hasOwnProperty('started')) {
$span.attr('title', 'Journey started: ' + $.formatDateTime("DD, dS MM yy 'at' g:iia", new Date(record.metadata.started)));
}
return $span;
});
$content.append($('<div/>')
.attr('class', 'glance-panel')
.append($('<img/>')
.attr('class', 'meta avatar')
.attr('src', function () {
return getAvatar( record.metadata.hasOwnProperty('rider') ? record.metadata.rider : undefined );
})
.attr('alt', rider)
// TODO: add a popup on hover with info about user
)
.append($('<ul/>')
.attr('class','stats')
.append($('<li/>')
// .attr('id', 'metric-distance-' + itemReference)
.attr('class', 'distance')
.text(turf.lineDistance(record.lineString).toPrecision(2) + 'km') // TODO: make this the title text and add infographic line
)
.append($('<li/>')
.attr('class', 'duration')
.append(duration)
)
.append($('<li/>')
.attr('class', 'sentiment')
.text('+' + record.goodPoints.length + ' / -' + record.badPoints.length) // TODO: make this (or similar) the title text and add infographic line
)
)
// TODO - sexy stats here
/* THIS WORKS ..
.append($('<img/>')
.attr('src','ui/images/stat-length.png')
)
*/
);
var $controls = $('<div/>')
.attr('class', 'map-controls')
.append($('<input/>')
.attr({
'type': 'checkbox',
'id': itemId,
'class': 'journey',
})
.change( function() {
// console.dir(loadedRecords[itemName]);
if (this.checked) {
//FIXME: neither the override idea or the enable/disable idea below work, but they don't break it :/
var styleOverride = {};
if (document.getElementById('color.' + itemId).value) {
styleOverride = {'color': document.getElementById('color.' + itemId).value,}
}
// console.log($.extend({}, config.rendering['viz-canvas'].lineStyle, styleOverride));
loadedRecords[itemName].showOn(map, styleOverride);
// document.getElementById('color.' + itemId).removeAttribute('disabled');
/* {
'color': $('#color.' + itemId).val(),
} */
}
else {
loadedRecords[itemName].hideOn(map);
// document.getElementById('color.' + itemId).setAttribute('disabled', 'disabled');
}
$(this).parents('#journeys li').toggleClass('showing');
})
)
.append($('<input/>')
.attr({
'type': 'color',
'id': 'color.' + itemId,
'class': 'color',
'title': 'Set Journey line colour',
})
// .attr('disabled', 'disabled')
.val(config.rendering['viz-canvas'].lineStyle.color)
/* // if I ever get a better colour popup (than the disappointing Spectrum)
.click( function(evt) {
evt.preventDefault();
})
*/
.change( function(evt) {
console.log(this.value);
if (loadedRecords[itemName].lineStringLayer) {
loadedRecords[itemName].lineStringLayer.setStyle({ // CHECKME: unclear from Leaflet docs, but this doesn't override any style options already set
'color': this.value,
});
}
})
/*
.spectrum({
showPalette: true,
showSelectionPalette: true,
maxSelectionSize: 8,
hideAfterPaletteSelect: true,
showInitial: true,
// showInput: true,
change: function(colour) {
console.log(colour);
loadedRecords[itemName].lineStringLayer.setStyle({ // CHECKME: ensure (unclear from Leaflet docs) that this doesn't override any style options already set
'color': colour.toHexString(),
});
}
})
*/
);
$item = $('<li/>')
.attr('id', 'li.' + itemId)
.append($controls)
.append($('<div/>')
.attr('class', 'hoozit')
.append($heading)
.append($content)
);
// .data('record', record);
// console.log($item.data('record'));
// $('#' + itemId).checkboxradio('refresh');
// TODO: add a button/link to zoom to the track's bounds
$('#journeys').prepend($item);
$('#journeys').listview('refresh');
}
loadedRecords[itemName] = record;
});
});
});
});
</script>
<script src="geo-leaflet.js" type="text/javascript"></script>
<script src="ui.js" type="text/javascript"></script>
</head>
<body>
<h1><img class="logo" src="ui/images/sensibel-logo-green.png" alt="Sensibel" /> Journey browser</h1>
<div class="track-explorer" id="track-explorer">
<div class="selector">
<ul id="journeys">
</ul>
</div>
<div id="viz-canvas" class="map"></div>
<div class="tools">
<!--
<input type="file" id="file" name="file" />
-->
<div id="log" class="output"></div>
</div>
</div>
<!-- <div id="meta" class="output"></div> -->
<script type="text/javascript">
// currently uses Amazon AWS which is pretty horrible interface-, metadata- and auth-wise and I would like to change
function journeyRecords(dataSource) {
this.list = function(onSuccess, onFail) { // TODO: onFail not implemented
items = $.get('http://' + dataSource.bucket + '.s3.amazonaws.com/?list-type=2&prefix=' + config.VIEWER_FILE_PREFIX );
items.done ( function(responseBody) {
$xml = $(responseBody);
resources = $xml.find('ListBucketResult Contents').toArray();
onSuccess && onSuccess(resources);
});
}
}
function journeyRecord(dataSource) {
var __this = this;
this['metadata'] = {};
this['points'] = [];
this['source'], this['GJ'], this['url'], this['filename'] = null;
this['layerGroup'], this['lineStringLayer'] = null;
this.load = function(name, onSuccess, onFail) {
this.filename = name;
this.url = 'http://' + dataSource.bucket + '.s3.amazonaws.com/' + this.filename;
var journey = $.get(this.url);
journey.done( function(responseBody) {
this.source = responseBody;
this.GJ = $.parseJSON(responseBody);
this.metadata = this.GJ.properties;
this['trail'] = _getTrail(this.GJ);
// TODO: from here on in, we could call a _stats() method eventually
this['lineString'] = _getLineString(this.GJ);
this['goodPoints'] = _getPoints(this.GJ, BUTTON_VALUE_GOOD);
this['badPoints'] = _getPoints(this.GJ, BUTTON_VALUE_BAD);
onSuccess && onSuccess(this);
});
}
var _isPoint = function(feature, valueFilter) {
return (feature.geometry.type == 'Point'
&& feature.properties
&& feature.properties.measure
&& feature.properties.measure == 'button'
&& ( valueFilter ? (feature.properties.value && (feature.properties.value == valueFilter)) : true )
);
}
var _getPoints = function(GJ, valueFilter) {
return GJ.features.filter( function(feature) {
return _isPoint(feature, valueFilter);
});
}
var _getTrail = function(GJ) {
var lineString = _getLineString(GJ);
if ( lineString ) {
return lineString.geometry.coordinates;
}
}
var _getLineString = function(GJ) {
if ( (GJ) && ( LineStrings = GJ.features.filter(_isLineString) ) ) {
return LineStrings[0]; // we'll just take the first, shouldn't be more than one
}
}
var _isLineString = function(feature) {
return (feature.geometry.type == 'LineString');
}
var _getPopupContent = function(properties) {
var displayValue = ( properties.value == BUTTON_VALUE_GOOD ? 'Sweet!' : ( properties.value == BUTTON_VALUE_BAD ? 'Stink' : properties.value ) ); // TODO: captions from config
var formattedDate = $.formatDateTime('D MM d, yy hh:ii', new Date(properties.time.replace('Z','+12:00'))); // see also http://momentjs.com
var markup = '<h2>' + displayValue + '</h2>\n<p>' + formattedDate + '</p>\n';
return markup;
}
this.showOn = function(targetMap, lineStyle) {
var lineStringLayer;
var featureIndex = 0;
var initialLineStyle = Object.assign({}, config.rendering['viz-canvas'].lineStyle, lineStyle ? lineStyle : {});
// NB order of this and subsequent L.geoJSON call is important - probably suboptimal architecture, should be refactored - be careful in the meantime!
var lineStringsLayerGroup = L.geoJson(this.GJ, {
'filter': function(feature, layer) {
return ( feature.geometry && feature.geometry.type && feature.geometry.type == 'LineString' );
},
'onEachFeature': function(feature, layer) {
layer.setStyle(initialLineStyle);
__this.lineStringLayer = layer; // FIXME; should really be an array or layerGroup as we could have more than one in the real world - see http://stackoverflow.com/a/19118143
featureIndex++;
}
});
// NB order of this and previous L.geoJSON call is important - probably suboptimal architecture, should be refactored - be careful in the meantime!
var pointsLayerGroup = L.geoJson(this.GJ, {
'filter': function(feature, layer) {
return ( feature.properties && feature.properties.measure && feature.properties.measure == 'button' );
},
'onEachFeature': function(feature, layer) {
// if (feature.properties && feature.properties.measure && feature.properties.measure == 'button') {
var hasCategory = feature.properties.hasOwnProperty('category');
var hasComment = feature.properties.hasOwnProperty('comment');
var hasAnnotations = hasCategory || hasComment;
var iconUrl = ( feature.properties.value == BUTTON_VALUE_GOOD ? 'ui/images/dot-pos.png' : 'ui/images/dot-neg.png' );
if (hasAnnotations) {
iconUrl = iconUrl.replace('.png', '-annotated.png');
}
var displayMarker = L.icon( {
'iconUrl': iconUrl, // TODO: icon URLs from config
'riseOnHover': true,
});
var popupContent = _getPopupContent(feature.properties);
__this.filename = __this.url.split('/').pop(); // *** whoa, I am just stumped why this filename property is lost at some point, but this restores it :/
// FIXME: categories not done properly here, read-only too
var categoryOptions;
categoryOptions += '<option></option>';
for (var i=0; i < categories.length; i++) {
categoryOptions += '<option value="' + categories[i] + '"';
if ( hasCategory && (feature.properties.category == categories[i]) ) {
categoryOptions += ' selected="selected"';
}
categoryOptions += '>';
categoryOptions += categories[i];
categoryOptions += '</option>\n';
}
// console.log('categoryOptions: ' + categoryOptions);
popupContent += ' \
<form name="annotate"> \
<input type="hidden" name="index" value="' + featureIndex + '" /> \
<input type="hidden" name="resource" value="' + __this.filename + '" /> \
<label for="category.' + + featureIndex + '">Category:</label> \
<select id="category.' + + featureIndex + '" name="category"> \
' + categoryOptions + ' \
</select> \
';
var commentValue = ( hasComment ? feature.properties.comment : '');
var placeHolder = 'What was so ' + (feature.properties.value == BUTTON_VALUE_GOOD ? 'good' : 'bad') + ' here?';
var commentForm = '<label for="comment.' + + featureIndex + '">Comment:</label> \
<textarea id="comment.' + + featureIndex + '" name="comment" placeholder="' + placeHolder + '">' + commentValue + '</textarea> \
<input type="button" value="Send" onclick="sendAnnotation(this.form);" /> \
</form> \
';
popupContent += commentForm;
layer.setIcon(displayMarker);
layer.bindPopup(popupContent);
featureIndex++;
},
});
// console.log(lineStringsLayerGroup);
this.layerGroup = pointsLayerGroup.addLayer(lineStringsLayerGroup);
this.layerGroup.addTo(targetMap);
if ( config.SHOW_TRACKPOINTS != 'none' ) {
targetMap.almostOver.addLayer(lineStringsLayerGroup);
var pointMarker = L.circleMarker( [-90,180], {
'color': 'white',
'weight': 5,
'radius': 8,
'fillOpacity': 0.2,
'fillColor': 'white',
})
if ( config.SHOW_TRACKPOINTS == 'properties' ) {
pointMarker.bindTooltip('trackpoint', {
'opacity':0.7,
'offset':[0,-4],
});
}
targetMap.on('almost:over', function (evt) {
targetMap.addLayer(pointMarker);
evt.layer.setStyle({ // TODO: style from config
'color': 'red',
});
});
targetMap.on('almost:move', function (evt) {
// TODO: simplify snap by using http://makinacorpus.github.io/Leaflet.GeometryUtil/global.html#closest
var line = evt.layer.feature;
var pt = turf.point([evt.latlng.lng, evt.latlng.lat]);
var snapped = turf.pointOnLine(line, pt);
// console.log(snapped);
var snappedLatLng = L.latLng(snapped.geometry.coordinates[1],snapped.geometry.coordinates[0]);
if ( config.SHOW_TRACKPOINTS == 'properties' ) {
var tooltipText;
if(line.properties && line.properties.coordinateProperties) {
tooltipText = 'times';
var coordinatedProperties = coordinatedPropertiesAt(snapped.geometry.coordinates, line);
tooltipText = formatCoordinatedProperties(coordinatedProperties, ['lat', 'lon']);
}
else {
tooltipText = 'trackpoint';
}
pointMarker.setTooltipContent(tooltipText);
}
pointMarker.setLatLng(snappedLatLng);
});
targetMap.on('almost:out', function (evt) {
targetMap.removeLayer(pointMarker);
evt.layer.setStyle(initialLineStyle);
});
targetMap.on('almost:click', function (evt) {
evt.layer.setStyle({ // TODO: style from config
'weight': 10,
});
evt.layer.openPopup();
});
}
// console.log('lineStringLayer: '); console.log(lineStringLayer);
this.lineStringLayer.bindPopup('<h2>Journey details</h2>\n' + formatAttributes(this.GJ));
// console.log('gJLayer: '); console.log(gJLayer);
targetMap.fitBounds(this.layerGroup.getBounds());
// FIXME: some redundancy below here!
var startMarker = L.icon( {
'iconUrl': 'ui/images/dot-start.png', // TODO: icon URLs from config
'title': 'Start',
});
var finishMarker = L.icon( {
'iconUrl': 'ui/images/dot-finish.png', // TODO: icon URLs from config
'title': 'Finish',
});
var started = this.lineStringLayer.getLatLngs()[0];
var finished = this.lineStringLayer.getLatLngs().last();
var startedProperties = {'value': 'Start',};
var finishedProperties = {'value': 'Finish',};
// console.log(__this.metadata.hasOwnProperty('started'));
if (__this.metadata.hasOwnProperty('started')) {
startedProperties['time'] = __this.metadata.started;
}
if (__this.metadata.hasOwnProperty('ended')) {
finishedProperties['time'] = __this.metadata.ended;
}
var startedPopup = _getPopupContent(startedProperties);
var finishedPopup = _getPopupContent(finishedProperties);
this.layerGroup.addLayer(L.marker(started, { 'icon': startMarker, }).bindPopup(startedPopup)).addTo(targetMap);
this.layerGroup.addLayer(L.marker(finished, { 'icon': finishMarker, }).bindPopup(finishedPopup)).addTo(targetMap);
}
this.hideOn = function(targetMap) {
this.layerGroup.eachLayer( function(layer) {
targetMap.removeLayer(layer);
} );
}
this.update = function() {
// TODO: some tests here to make sure there is something loaded
var uploadTarget = this.url;
var req = $.ajax({
type: 'PUT',
url: uploadTarget,
// dataType: 'json', // FIXME: failing because it doesn't vallidate as JSON, probably start looking at makegeoJSON
async: true,
data: JSON.stringify(this.GJ),
});
req.done( function(msg) {
console.log('Update to ' + uploadTarget + ' succeeded: ' + msg);
});
req.fail( function(xhr, failText) {
console.log('Error ' + xhr.status + ': ' + failText);
});
};
}
var sendAnnotation = function(frm) {
var fields = {};
var $relevantFields = $(frm).find(':checkbox,input[type="text"],input[type="hidden"],:radio,:password,textarea,select');
$relevantFields.each( function() {
fields[$(this).attr('name')] = $(this).val();
});
var GJ = loadedRecords[fields.resource].GJ;
var feature = GJ.features[fields.index];
feature.properties['category'] = fields.category;
feature.properties['comment'] = fields.comment;
loadedRecords[fields.resource].update();
// refresh map
loadedRecords[fields.resource].showOn(map);
// some feedback
$(frm).append('<p class="success">Updated</p>');
};
var coordinatedPropertiesAt = function(coordinates, timedLineString) {
var result = [];
if (timedLineString.properties && timedLineString.properties.coordinateProperties) {
var aligned = consolidateTimestampedLineString(timedLineString);
var matched = aligned.filter( function(item, index) {
return ( item.lat == coordinates[1] && item.lon == coordinates[0] );
});
result = result.concat(matched);
}
return result;
};
var pivotCoordinatedProperties = function(coordinatedProperties) {
var result = {};
// console.log(coordinatedProperties[0]);
// if (coordinatedProperties.length > 0) {
Object.keys(coordinatedProperties[0]).forEach( function(propertyName) {
result[propertyName] = [];
for(i=0 ; i < coordinatedProperties.length ; i++) {
// TODO - null values
result[propertyName].push(coordinatedProperties[i][propertyName]);
}
});
// }
return result;
};
var formatCoordinatedProperties = function(coordinatedProperties, exclusions, labels) {
exclusions = exclusions || [];
var listDelimiter = ',';
var lineDelimiter = '\n';
var resultLines = [];
var coordinateProperties = pivotCoordinatedProperties(coordinatedProperties);
// TODO - just handling nice labels for 'times' coordinate property at present
$.each(coordinateProperties, function(key, values) {
if (!exclusions.includes(key)) {
var label = key;
values = values.filter( function(value) { // eliminate null and undefined members
return value;
});
if (key == 'times' ) {
label = 'Times';
values = values.map( function(timestamp) {
return $.formatDateTime("'<strong>'hh:ii'</strong>':ss", new Date(timestamp));
});
}
resultLines.push( ( labels ? label + ': ' : '' ) + values.join(listDelimiter));
}
});
return resultLines.join(lineDelimiter);
};
var consolidateTimestampedLineString = function(timedLineString) {
var result = [];
if (timedLineString.properties && timedLineString.properties.coordinateProperties) { // life is like a box of chocolates ..
for(i=0 ; i < timedLineString.geometry.coordinates.length ; i++) {
var member = {
'lat': timedLineString.geometry.coordinates[i][1],
'lon': timedLineString.geometry.coordinates[i][0],
};
Object.keys(timedLineString.properties.coordinateProperties).forEach( function(propertyName) {
member[propertyName] = timedLineString.properties.coordinateProperties[propertyName][i];
});
result.push(member);
}
}
return result;
};
// TODO: stub that returns geneic avatars until we have a system!
var getAvatar = function(userName) {
if(userName) {
// console.log('Username given: ' + userName);
return 'http://lorempixel.com/g/32/32/cats/'; // + userName;
}
return 'ui/images/user.placeholder.png';
};
</script>
</body>