forked from datadesk/timemap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtimemap.js
2769 lines (2566 loc) · 94.2 KB
/
timemap.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
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
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*!
* Timemap.js Copyright 2008 Nick Rabinowitz.
* Licensed under the MIT License (see LICENSE.txt)
*/
/*global SimileAjax */
/*jslint es6, this */
/**
* @overview
*
* <p>Timemap.js is intended to sync a SIMILE Timeline with a web-based map.
* Thanks to Jorn Clausen (https://www.oe-files.de) for initial concept and code.
* Timemap.js is licensed under the MIT License (see <a href="../LICENSE.txt">LICENSE.txt</a>).</p>
* <p><strong>Depends on:</strong>
* <a href="https://jquery.com">jQuery</a>,
* <a href="https://github.com/nrabinowitz/mxn"> a customized version of Mapstraction 2.x<a>,
* a map provider of your choice, <a href="code.google.com/p/simile-widgets">SIMILE Timeline v1.2 - 2.3.1.</a>
* </p>
* <p><strong>Tested browsers:</strong> Firefox 3.x, Google Chrome, <s>IE7, IE8</s></p>
* <p><strong>Tested map providers:</strong>
* <s><a href="https://code.google.com/apis/maps/documentation/javascript/v2/reference.html">Google v2</a>,</s>
* <a href="https://code.google.com/apis/maps/documentation/javascript/reference.html">Google v3</a>,
* <a href="https://openlayers.org">OpenLayers</a>,
* <s><a href="https://msdn.microsoft.com/en-us/library/bb429565.aspx">Bing Maps</a></s>
* </p>
* <ul>
* <li><a href="https://code.google.com/p/timemap/">Project Homepage</a></li>
* <li><a href="https://groups.google.com/group/timemap-development">Discussion Group</a></li>
* <li><a href="../examples/index.html">Working Examples</a></li>
* </ul>
*
* @name timemap.js
* @author Nick Rabinowitz (www.nickrabinowitz.com)
* @version 2.1pre
*/
(function () {
// borrowing some space-saving devices from jquery
var
// Will speed up references to window, and allows munging its name.
window = this,
// Will speed up references to undefined, and allows munging its name.
undefined,
// aliases for Timeline objects
Timeline = window.Timeline, DateTime = Timeline.DateTime,
// alias libraries
$ = window.jQuery,
mxn = window.mxn,
// alias Mapstraction classes
Mapstraction = mxn.Mapstraction,
LatLonPoint = mxn.LatLonPoint,
BoundingBox = mxn.BoundingBox,
Marker = mxn.Marker,
Polyline = mxn.Polyline,
// events
E_ITEMS_LOADED = 'itemsloaded',
// Google icon path
GIP = "https://www.google.com/intl/en_us/mapfiles/ms/icons/",
// aliases for class names, allowing munging
TimeMap, TimeMapFilterChain, TimeMapDataset, TimeMapTheme, TimeMapItem;
/*----------------------------------------------------------------------------
* TimeMap Class
*---------------------------------------------------------------------------*/
/**
* The TimeMap object holds references to timeline, map, and datasets.
*
* This will create the visible map, but not the timeline, which must be initialized separately.
*
* @param {HTMLElement} tElement The timeline element.
* @param {HTMLElement} mElement The map element.
* @param {Object} [options] A container for optional arguments
* @param {TimeMapTheme|String} [options.theme=red] Color theme for the timemap
* @param {Boolean} [options.syncBands=true] Whether to synchronize all bands in timeline
* @param {LatLonPoint} [options.mapCenter=0,0] Point for map center
* @param {Number} [options.mapZoom=0] Initial map zoom level
* @param {String} [options.mapType=physical] The maptype for the map (see {@link TimeMap.mapTypes} for options)
* @param {Function|String} [options.mapFilter={@link TimeMap.filters.hidePastFuture}]
* How to hide/show map items depending on timeline state;
* options: keys in {@link TimeMap.filters} or function. Set to
* null or false for no filter.
* @param {Boolean} [options.showMapTypeCtrl=true] Whether to display the map type control
* @param {Boolean} [options.showMapCtrl=true] Whether to show map navigation control
* @param {Boolean} [options.centerOnItems=true] Whether to center and zoom the map based on loaded item
* @param {String} [options.eventIconPath] Path for directory holding event icons; if set at the TimeMap
* level, will override dataset and item defaults
* @param {Boolean} [options.checkResize=true] Whether to update the timemap display when the window is
* resized. Necessary for fluid layouts, but might be better set to
* false for absolutely-sized timemaps to avoid extra processing
* @param {Boolean} [options.multipleInfoWindows=false] Whether to allow multiple simultaneous info windows for
* map providers that allow this (Google v3, OpenLayers)
* @param {mixed} [options[...]] Any of the options for {@link TimeMapDataset},
* {@link TimeMapItem}, or {@link TimeMapTheme} may be set here,
* to cascade to the entire TimeMap, though they can be overridden
* at lower levels
* </pre>
* @constructor
*/
TimeMap = function (tElement, mElement, options) {
var tm = this,
// set defaults for options
defaults = {
mapCenter: new LatLonPoint(0, 0),
mapZoom: 0,
mapType: 'physical',
showMapTypeCtrl: true,
showMapCtrl: true,
syncBands: true,
mapFilter: 'hidePastFuture',
centerOnItems: true,
theme: 'red',
dateParser: 'hybrid',
checkResize: true,
multipleInfoWindows: false
},
mapCenter;
// save DOM elements
/**
* Map element
* @name TimeMap#mElement
* @type HTMLElement
*/
tm.mElement = mElement;
/**
* Timeline element
* @name TimeMap#tElement
* @type HTMLElement
*/
tm.tElement = tElement;
/**
* Map of datasets
* @name TimeMap#datasets
* @type Object
*/
tm.datasets = {};
/**
* Filter chains for this timemap
* @name TimeMap#chains
* @type Object
*/
tm.chains = {};
/**
* Container for optional settings passed in the "options" parameter
* @name TimeMap#opts
* @type Object
*/
tm.opts = options = $.extend(defaults, options);
// allow map center to be specified as a point object
mapCenter = options.mapCenter;
if (mapCenter.constructor !== LatLonPoint && mapCenter.lat) {
options.mapCenter = new LatLonPoint(mapCenter.lat, mapCenter.lon);
}
// allow map types to be specified by key
options.mapType = util.lookup(options.mapType, TimeMap.mapTypes);
// allow map filters to be specified by key
options.mapFilter = util.lookup(options.mapFilter, TimeMap.filters);
// allow theme options to be specified in options
options.theme = TimeMapTheme.create(options.theme, options);
// initialize map
tm.initMap();
};
// STATIC FIELDS
/**
* Current library version.
* @constant
* @type String
*/
TimeMap.version = "2.1pre";
/**
* @name TimeMap.util
* Namespace for TimeMap utility functions.
* @namespace TimeMap.util
*/
var util = TimeMap.util = {};
// STATIC METHODS
/**
* Intializes a TimeMap.
*
* <p>The idea here is to throw all of the standard intialization settings into
* a large object and then pass it to the TimeMap.init() function. The full
* data format is outlined below, but if you leave elements out the script
* will use default settings instead.</p>
*
* <p>See the examples and the
* <a href="https://code.google.com/p/timemap/wiki/UsingTimeMapInit">UsingTimeMapInit wiki page</a>
* for usage.</p>
*
* @param {Object} config Full set of configuration options.
* @param {String} [config.mapId] DOM id of the element to contain the map.
* Either this or mapSelector is required.
* @param {String} [config.timelineId] DOM id of the element to contain the timeline.
* Either this or timelineSelector is required.
* @param {String} [config.mapSelector] jQuery selector for the element to contain the map.
* Either this or mapId is required.
* @param {String} [config.timelineSelector] jQuery selector for the element to contain the timeline.
* Either this or timelineId is required.
* @param {Object} [config.options] Options for the TimeMap object (see the {@link TimeMap} constructor)
* @param {Object[]} config.datasets Array of datasets to load
* @param {Object} config.datasets[x] Configuration options for a particular dataset
* @param {String|Class} config.datasets[x].type Loader type for this dataset (generally a sub-class
* of {@link TimeMap.loaders.base})
* @param {Object} config.datasets[x].options Options for the loader. See the {@link TimeMap.loaders.base}
* constructor and the constructors for the various loaders for
* more details.
* @param {String} [config.datasets[x].id] Optional id for the dataset in the {@link TimeMap#datasets}
* object, for future reference; otherwise "ds"+x is used
* @param {String} [config.datasets[x][...]] Other options for the {@link TimeMapDataset} object
* @param {String|Array} [config.bandIntervals=wk] Intervals for the two default timeline bands. Can either be an
* array of interval constants or a key in {@link TimeMap.intervals}
* @param {Object[]} [config.bandInfo] Array of configuration objects for Timeline bands, to be passed to
* Timeline.createBandInfo (see the <a href="https://code.google.com/p/simile-widgets/wiki/Timeline_GettingStarted">Timeline Getting Started tutorial</a>).
* This will override config.bandIntervals, if provided.
* @param {Timeline.Band[]} [config.bands] Array of instantiated Timeline Band objects. This will override
* config.bandIntervals and config.bandInfo, if provided.
* @param {Function} [config.dataLoadedFunction] Function to be run as soon as all datasets are loaded, but
* before they've been displayed on the map and timeline
* (this will override dataDisplayedFunction and scrollTo)
* @param {Function} [config.dataDisplayedFunction] Function to be run as soon as all datasets are loaded and
* displayed on the map and timeline
* @param {String|Date} [config.scrollTo=earliest] Date to scroll to once data is loaded - see
* {@link TimeMap.parseDate} for options
* @return {TimeMap} The initialized TimeMap object
*/
TimeMap.init = function (config) {
var //err = "TimeMap.init: Either %Id or %Selector is required",
// set defaults
defaults = {
options: {},
datasets: [],
bands: false,
bandInfo: false,
bandIntervals: "wk",
scrollTo: "earliest"
},
state = TimeMap.state,
intervals, tm,
datasets = [], dsOptions, dsId, //topOptions, x,
bands = [], eventSource;
// get DOM element selectors
config.mapSelector = config.mapSelector || '#' + config.mapId;
config.timelineSelector = config.timelineSelector || '#' + config.timelineId;
// get state from url hash if state functions are available
if (state) {
state.setConfigFromUrl(config);
}
// merge options and defaults
config = $.extend(defaults, config);
if (!config.bandInfo && !config.bands) {
// allow intervals to be specified by key
intervals = util.lookup(config.bandIntervals, TimeMap.intervals);
// make default band info
config.bandInfo = [
{
width: "80%",
intervalUnit: intervals[0],
intervalPixels: 70
},
{
width: "20%",
intervalUnit: intervals[1],
intervalPixels: 100,
showEventText: false,
overview: true,
trackHeight: 0.4,
trackGap: 0.2
}
];
}
// create the TimeMap object
tm = new TimeMap(
$(config.timelineSelector).get(0),
$(config.mapSelector).get(0),
config.options
);
// create the dataset objects
config.datasets.forEach(function (ds, x) {
// put top-level data into options
dsOptions = $.extend({
title: ds.title,
theme: ds.theme,
dateParser: ds.dateParser
}, ds.options);
dsId = ds.id || "ds" + x;
datasets[x] = tm.createDataset(dsId, dsOptions);
if (x > 0) {
// set all to the same eventSource
datasets[x].eventSource = datasets[0].eventSource;
}
});
// add a pointer to the eventSource in the TimeMap
tm.eventSource = datasets[0].eventSource;
// set up timeline bands
// ensure there's at least an empty eventSource
eventSource = (datasets[0] && datasets[0].eventSource) || new Timeline.DefaultEventSource();
// check for pre-initialized bands (manually created with Timeline.createBandInfo())
if (config.bands) {
config.bands.forEach(function (band) {
// substitute dataset event source
// assume that these have been set up like "normal" Timeline bands:
// with an empty event source if events are desired, and null otherwise
if (band.eventSource !== null) {
band.eventSource = eventSource;
}
});
bands = config.bands;
}
// otherwise, make bands from band info
else {
config.bandInfo.forEach(function (bandInfo, x) {
// if eventSource is explicitly set to null or false, ignore
if ( bandInfo.hasOwnProperty('eventSource') && !bandInfo.eventSource ) {
bandInfo.eventSource = null;
}
else {
bandInfo.eventSource = eventSource;
}
bands[x] = Timeline.createBandInfo(bandInfo);
if (x > 0 && util.TimelineVersion() === "1.2") {
// set all to the same layout
bands[x].eventPainter.setLayout(bands[0].eventPainter.getLayout());
}
});
}
// initialize timeline
tm.initTimeline(bands);
// initialize load manager
var loadManager = TimeMap.loadManager,
callback = function () {
loadManager.increment();
};
loadManager.init(tm, config.datasets.length, config);
// load data!
config.datasets.forEach(function (data, x) {
var dataset = datasets[x],
options = data.data || data.options || {},
type = data.type || options.type,
// get loader class
loaderClass = (typeof type === 'string') ? TimeMap.loaders[type] : type,
// load with appropriate loader
loader = new loaderClass(options);
loader.load(dataset, callback);
});
// return timemap object for later manipulation
return tm;
};
// METHODS
TimeMap.prototype = {
/**
*
* Initialize the map.
*/
initMap: function () {
var tm = this,
options = tm.opts,
map;
/**
* The Mapstraction object
* @name TimeMap#map
* @type Mapstraction
*/
tm.map = map = new Mapstraction(tm.mElement, options.mapProvider);
// display the map centered on a latitude and longitude
map.setCenterAndZoom(options.mapCenter, options.mapZoom);
// set default controls and map type
map.addControls({
pan: options.showMapCtrl,
zoom: options.showMapCtrl ? 'large' : false,
map_type: options.showMapTypeCtrl
});
map.setMapType(options.mapType);
// allow multiple windows if desired
if (options.multipleInfoWindows) {
map.setOption('enableMultipleBubbles', true);
}
/**
* Return the native map object (specific to the map provider)
* @name TimeMap#getNativeMap
* @function
* @return {Object} The native map object (e.g. GMap2)
*/
tm.getNativeMap = function () { return map.getMap(); };
},
/**
* Initialize the timeline - this must happen separately to allow full control of
* timeline properties.
*
* @param {BandInfo[]} bands Array of band information objects for timeline
*/
initTimeline: function (bands) {
var tm = this, timeline,
opts = tm.opts,
// filter: hide when item is hidden
itemVisible = function (item) {
return item.visible;
},
// filter: hide when dataset is hidden
datasetVisible = function (item) {
return item.dataset.visible;
},
// handler to open item window
eventClickHandler = function (ignore, _ignore, evt) {
evt.item.openInfoWindow();
},
resizeTimerID, x, painter;
// synchronize & highlight timeline bands
bands.slice(1).forEach( function (band) {
if (opts.syncBands) {
band.syncWith = 0;
}
band.highlight = true;
});
/**
* The associated timeline object
* @name TimeMap#timeline
* @type Timeline
*/
tm.timeline = timeline = Timeline.create(tm.tElement, bands);
// hijack timeline popup window to open info window
for (x = 0; x < timeline.getBandCount(); x+=1) {
painter = timeline.getBand(x).getEventPainter().constructor;
painter.prototype._showBubble = eventClickHandler;
}
// filter chain for map placemarks
tm.addFilterChain("map",
// on
function (item) {
item.showPlacemark();
},
// off
function (item) {
item.hidePlacemark();
},
// pre/post
null, null,
// initial chain
[itemVisible, datasetVisible]
);
// filter: hide map items depending on timeline state
if (opts.mapFilter) {
tm.addFilter("map", opts.mapFilter);
// update map on timeline scroll
timeline.getBand(0).addOnScrollListener(function () {
tm.filter("map");
});
}
// filter chain for timeline events
tm.addFilterChain("timeline",
// on
function (item) {
item.showEvent();
},
// off
function (item) {
item.hideEvent();
},
// pre
null,
// post
function () {
// XXX: needed if we go to Timeline filtering?
tm.eventSource._events._index();
timeline.layout();
},
// initial chain
[itemVisible, datasetVisible]
);
// filter: hide timeline items depending on map state
if (opts.timelineFilter) {
tm.addFilter("map", opts.timelineFilter);
}
// add callback for window resize, if necessary
if (opts.checkResize) {
window.onresize = function () {
if (!resizeTimerID) {
resizeTimerID = window.setTimeout(function () {
resizeTimerID = null;
timeline.layout();
}, 500);
}
};
}
},
/**
* Parse a date in the context of the timeline. Uses the standard parser
* ({@link TimeMap.dateParsers.hybrid}) but accepts "now", "earliest",
* "latest", "first", and "last" (referring to loaded events)
*
* @param {String|Date} s String (or date) to parse
* @return {Date} Parsed date
*/
parseDate: function (s) {
var d = new Date(),
eventSource = this.eventSource,
parser = TimeMap.dateParsers.hybrid,
// make sure there are events to scroll to
hasEvents = Boolean(eventSource.getCount() > 0);
switch (s) {
case "now":
break;
case "earliest":
case "first":
if (hasEvents) {
d = eventSource.getEarliestDate();
}
break;
case "latest":
case "last":
if (hasEvents) {
d = eventSource.getLatestDate();
}
break;
default:
// assume it's a date, try to parse
d = parser(s);
}
return d;
},
/**
* Scroll the timeline to a given date. If lazyLayout is specified, this function
* will also call timeline.layout(), but only if it won't be called by the
* onScroll listener. This involves a certain amount of reverse engineering,
* and may not be future-proof.
*
* @param {String|Date} d Date to scroll to (either a date object, a
* date string, or one of the strings accepted
* by TimeMap#parseDate)
* @param {Boolean} [lazyLayout] Whether to call timeline.layout() if not
* required by the scroll.
* @param {Boolean} [animated] Whether to do an animated scroll, rather than a jump.
*/
scrollToDate: function (d, lazyLayout, animated) {
var timeline = this.timeline,
topband = timeline.getBand(0),
x, time, layouts = [],
band, minTime, maxTime;
d = this.parseDate(d);
if (d) {
time = d.getTime();
// check which bands will need layout after scroll
for (x = 0; x < timeline.getBandCount(); x+=1) {
band = timeline.getBand(x);
minTime = band.getMinDate().getTime();
maxTime = band.getMaxDate().getTime();
layouts[x] = (lazyLayout && minTime < time && time < maxTime);
}
// do scroll
if (animated) {
// create animation
var provider = util.TimelineVersion() === '1.2' ? Timeline : SimileAjax,
a = provider.Graphics.createAnimation(function (abs) {
topband.setCenterVisibleDate(new Date(abs));
}, topband.getCenterVisibleDate().getTime(), time, 1000);
a.run();
}
else {
topband.setCenterVisibleDate(d);
}
// layout as necessary
layouts.forEach( function (layout,x) {
if (layout) {
timeline.getBand(x).layout();
}
});
}
// layout if requested even if no date is found
else if (lazyLayout) {
timeline.layout();
}
},
/**
* Create an empty dataset object and add it to the timemap
*
* @param {String} id The id of the dataset
* @param {Object} options A container for optional arguments for dataset constructor -
* see the options passed to {@link TimeMapDataset}
* @return {TimeMapDataset} The new dataset object
*/
createDataset: function (id, options) {
var tm = this,
dataset = new TimeMapDataset(tm, options),
map;
// save id reference
dataset.id = id;
tm.datasets[id] = dataset;
// add event listener
if (tm.opts.centerOnItems) {
map = tm.map;
$(dataset).bind(E_ITEMS_LOADED, function () {
// determine the center and zoom level from the bounds
map.autoCenterAndZoom();
});
}
return dataset;
},
/**
* Run a function on each dataset in the timemap. This is the preferred
* iteration method, as it allows for future iterator options.
*
* @param {Function} f The function to run, taking one dataset as an argument
*/
each: function (f) {
var tm = this;
Object.values(tm.datasets).forEach(f);
},
/**
* Run a function on each item in each dataset in the timemap.
* @param {Function} f The function to run, taking one item as an argument
*/
eachItem: function (f) {
this.each(function (ds) {
ds.each(function (item) {
f(item);
});
});
},
/**
* Get all items from all datasets.
* @return {TimeMapItem[]} Array of all items
*/
getItems: function () {
var items = [];
this.each(function (ds) {
items = items.concat(ds.items);
});
return items;
},
/**
* Save the currently selected item
* @param {TimeMapItem|String} item Item to select, or undefined
* to clear selection
*/
setSelected: function (item) {
this.opts.selected = item;
},
/**
* Get the currently selected item
* @return {TimeMapItem} Selected item
*/
getSelected: function () {
return this.opts.selected;
},
// Helper functions for dealing with filters
/**
* Update items, hiding or showing according to filters
* @param {String} chainId Filter chain to update on
*/
filter: function (chainId) {
var fc = this.chains[chainId];
if (fc) {
fc.run();
}
},
/**
* Add a new filter chain
*
* @param {String} chainId Id of the filter chain
* @param {Function} fon Function to run on an item if filter is true
* @param {Function} foff Function to run on an item if filter is false
* @param {Function} [pre] Function to run before the filter runs
* @param {Function} [post] Function to run after the filter runs
* @param {Function[]} [chain] Optional initial filter chain
*/
addFilterChain: function (chainId, fon, foff, pre, post, chain) {
this.chains[chainId] = new TimeMapFilterChain(this, fon, foff, pre, post, chain);
},
/**
* Remove a filter chain
*
* @param {String} chainId Id of the filter chain
*/
removeFilterChain: function (chainId) {
delete this.chains[chainId];
},
/**
* Add a function to a filter chain
*
* @param {String} chainId Id of the filter chain
* @param {Function} f Function to add
*/
addFilter: function (chainId, f) {
var fc = this.chains[chainId];
if (fc) {
fc.add(f);
}
},
/**
* Remove a function from a filter chain
*
* @param {String} chainId Id of the filter chain
* @param {Function} [f] The function to remove
*/
removeFilter: function (chainId, f) {
var fc = this.chains[chainId];
if (fc) {
fc.remove(f);
}
}
};
/*----------------------------------------------------------------------------
* Load manager
*---------------------------------------------------------------------------*/
/**
* @class Static singleton for managing multiple asynchronous loads
*/
TimeMap.loadManager = new function () {
var mgr = this;
/**
* Initialize (or reset) the load manager
* @name TimeMap.loadManager#init
* @function
*
* @param {TimeMap} tm TimeMap instance
* @param {Number} target Number of datasets we're loading
* @param {Object} [options] Container for optional settings
* @param {Function} [options.dataLoadedFunction]
* Custom function replacing default completion function;
* should take one parameter, the TimeMap object
* @param {String|Date} [options.scrollTo]
* Where to scroll the timeline when load is complete
* Options: "earliest", "latest", "now", date string, Date
* @param {Function} [options.dataDisplayedFunction]
* Custom function to fire once data is loaded and displayed;
* should take one parameter, the TimeMap object
*/
mgr.init = function (tm, target, config) {
mgr.count = 0;
mgr.tm = tm;
mgr.target = target;
mgr.opts = config || {};
};
/**
* Increment the count of loaded datasets
* @name TimeMap.loadManager#increment
* @function
*/
mgr.increment = function () {
mgr.count+=1;
if (mgr.count >= mgr.target) {
mgr.complete();
}
};
/**
* Function to fire when all loads are complete.
* Default behavior is to scroll to a given date (if provided) and
* layout the timeline.
* @name TimeMap.loadManager#complete
* @function
*/
mgr.complete = function () {
var tm = mgr.tm,
opts = mgr.opts,
// custom function including timeline scrolling and layout
func = opts.dataLoadedFunction;
if (func) {
func(tm);
}
else {
tm.scrollToDate(opts.scrollTo, true);
// check for state support
if (tm.initState) {
tm.initState();
}
// custom function to be called when data is loaded
func = opts.dataDisplayedFunction;
if (func) {
func(tm);
}
}
};
}();
/*----------------------------------------------------------------------------
* Loader namespace and base classes
*---------------------------------------------------------------------------*/
/**
* Namespace for different data loader functions.
* New loaders can add their factories or constructors to this object; loader
* functions are passed an object with parameters in TimeMap.init().
*
* @example
TimeMap.init({
datasets: [
{
// name of class in TimeMap.loaders
type: "json_string",
options: {
url: "mydata.json"
},
// etc...
}
],
// etc...
});
* @namespace TimeMap.loaders
*/
TimeMap.loaders = {
/**
* Object for storing callback functions
* @private
*/
cb: {},
/**
* Cancel a specific load request. In practice, this is really only
* applicable to remote asynchronous loads. Note that this doesn't cancel
* the download of data, just the callback that loads it.
* @param {String} callbackName Name of the callback function to cancel
*/
cancel: function (callbackName) {
var namespace = TimeMap.loaders.cb;
// is namespace the right word here?
// replace with self-cancellation function
namespace[callbackName] = function () {
delete namespace[callbackName];
};
},
/**
* Cancel all current load requests.
*/
cancelAll: function () {
const loaderNS = TimeMap.loaders;
Object.keys(loaderNS.cb).forEach(loaderNS.cancel.bind(loaderNS));
},
/**
* Static counter for naming callback functions
* @private
* @type int
*/
counter: 0,
/**
* @class
* Abstract loader class. All loaders should inherit from this class.
*
* @constructor
* @param {Object} options All options for the loader
* @param {Function} [options.parserFunction=Do nothing]
* Parser function to turn a string into a JavaScript array
* @param {Function} [options.preloadFunction=Do nothing]
* Function to call on data before loading
* @param {Function} [options.transformFunction=Do nothing]
* Function to call on individual items before loading
* @param {String|Date} [options.scrollTo=earliest] Date to scroll the timeline to in the default callback
* (see {@link TimeMap#parseDate} for accepted syntax)
*/
base: function (options) {
var dummy = function (data) { return data; },
loader = this;
/**
* Parser function to turn a string into a JavaScript array
* @name TimeMap.loaders.base#parse
* @function
* @parameter {String} s String to parse
* @return {Object[]} Array of item data
*/
loader.parse = options.parserFunction || dummy;
/**
* Function to call on data object before loading
* @name TimeMap.loaders.base#preload
* @function
* @parameter {Object} data Data to preload
* @return {Object[]} Array of item data
*/
loader.preload = options.preloadFunction || dummy;
/**
* Function to call on a single item data object before loading
* @name TimeMap.loaders.base#transform
* @function
* @parameter {Object} data Data to transform
* @return {Object} Transformed data for one item
*/
loader.transform = options.transformFunction || dummy;
/**
* Date to scroll the timeline to on load
* @name TimeMap.loaders.base#scrollTo
* @default "earliest"
* @type String|Date
*/
loader.scrollTo = options.scrollTo || "earliest";
/**
* Get the name of a callback function that can be cancelled. This callback applies the parser,
* preload, and transform functions, loads the data, then calls the user callback
* @name TimeMap.loaders.base#getCallbackName
* @function
*
* @param {TimeMapDataset} dataset Dataset to load data into
* @param {Function} callback User-supplied callback function. If no function
* is supplied, the default callback will be used
* @return {String} The name of the callback function in TimeMap.loaders.cb
*/
loader.getCallbackName = function (dataset, callback) {
var callbacks = TimeMap.loaders.cb,
// Define a unique function name
callbackName = "_" + TimeMap.loaders.counter;
TimeMap.loaders.counter += 1;
// Define default callback
callback = callback || function () {
dataset.timemap.scrollToDate(loader.scrollTo, true);
};
// create callback
callbacks[callbackName] = function (result) {
// parse
var items = loader.parse(result);
// preload
items = loader.preload(items);
// load
dataset.loadItems(items, loader.transform);
// callback
callback();
// delete the callback function
delete callbacks[callbackName];
};
return callbackName;
};
/**
* Get a callback function that can be cancelled. This is a convenience function
* to be used if the callback name itself is not needed.
* @name TimeMap.loaders.base#getCallback
* @function
* @see TimeMap.loaders.base#getCallbackName
*
* @param {TimeMapDataset} dataset Dataset to load data into
* @param {Function} callback User-supplied callback function
* @return {Function} The configured callback function
*/
loader.getCallback = function (dataset, callback) {
// get loader callback name
var callbackName = loader.getCallbackName(dataset, callback);
// return the function