-
Notifications
You must be signed in to change notification settings - Fork 2
/
dataninja-advanced-mapping-tool.js
2372 lines (1996 loc) · 109 KB
/
dataninja-advanced-mapping-tool.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
if (mapConfig) {
// Known sources of data with global setting inherited to datasets with 'source' parameter
mapConfig.dataSources = {
// Dataset embedded in the geo layer (no joining with external data)
shape: {},
// Local or remote static file
file: {
// Domain without trailing slash (only for remote file)
domain: '',
// Relative or absolute path (with trailing slash)
path: '',
// Complete file name if single file (with extension)
filename: '',
// File format (used also as extension in file name template for multiple files)
format: '',
// URL generator based on region and a filter
url: function(region, filterKey, filterValue) {
/* Default file name template if filename is empty:
* - region_filterKey-filterValue.format
* If no filter:
* - region.format
*/
return this.domain +
this.path +
(this.filename || (region + (filterKey && filterValue ? '_'+filterKey+'-'+filterValue : '') + "." + this.format));
},
// Callback function of ajax request for custom result transformation
// this is the dataSet object
transform: function(res) {
return res;
}
},
// Dkan API: see http://docs.getdkan.com/docs/dkan-documentation/dkan-api/datastore-api
dkan: {
// Domain without trailing slash
domain: '',
/* Relative or absolute path (ie. [prepath]/action/datastore/search.json)
* See http://docs.getdkan.com/docs/dkan-documentation/dkan-api/datastore-api#Datastore_API_URL_
*/
path: '',
/* Request parameters for Dkan API
* See http://docs.getdkan.com/docs/dkan-documentation/dkan-api/datastore-api#Request_Parameters
*/
// UID of the resource
resourceId: '',
// Limit returned items number in response
limit: 5000,
// Format of response (ie. json)
format: 'json',
// URL generator based on region and a filter
url: function(region, filterKey, filterValue) {
return this.domain + this.path +
'?resource_id=' + this.resourceId +
(filterKey && filterValue ? ('&filters[' + filterKey + ']=' + filterValue) : '') +
(this.limit ? '&limit=' + this.limit : '');
},
/* Callback function of ajax request for custom result transformation
* this is the dataSet object
* See http://docs.getdkan.com/docs/dkan-documentation/dkan-api/datastore-api#Return_Values
*/
transform: function(res) {
return res.result.records;
}
}
};
}
/*
* Map configuration complete structure:
*
* - dataSources [object]
* - shape [empty object]
* - file [object]
* - domain [string]
* - path [string]
* - filename [string]
* - format [string]
* - url [string] function ( [string], [string], [string | int] )
* - transform [array] function ( [mixed] )
* - dkan [object]
* - domain [string]
* - path [string]
* - resourceId [string]
* - limit [int > 0]
* - format [string]
* - url [string] function ( [string], [string], [string | int] )
* - transform [array] function ( [object] )
*/
;if (mapConfig) {
// Known types of data with global setting inherited to datasets with 'type' parameter
mapConfig.dataTypes = {
/* Choropleth (also known as thematic map):
* regions are colored based on data values
*/
choropleth: {
/* Fillcolor when based on data
* Palette names refer to colorbrewer2 lib
* See http://colorbrewer2.org/
*/
palette: 'Reds',
// Rounding factor for binning bounds, in 10^n with n is an integer (positive or negative)
// 0 means no rounding
precision: 0,
// Bins number for data -> color scale transformation
bins: 3
},
// Simple points with latitude and longitude shown as markers TODO
points: {}
};
}
/*
* Map configuration complete structure:
*
* - dataTypes [object]
* - choropleth [object]
* - palette [string]
* - precision 10^[int]
* - bins [int > 0]
* - points [object]
*/
;if (mapConfig) {
// Known sources of geo shapes with global setting inherited to geolayers with 'source' parameter
mapConfig.geoSources = {
// Local or remote static file
file: {
// Domain without trailing slash (only for remote file)
domain: '',
// Relative or absolute path (with trailing slash)
path: '',
/* File format (used as extension in file name template for multiple files)
* Geojson is the default format, see http://geojson.org/
*/
format: 'geojson',
// Complete file name if single file (with extension)
filename: '',
// URL generator
url: function(region, filterKey, filterValue) {
return this.domain +
this.path +
(this.filename || (region + (filterKey && filterValue ? '_'+filterKey+'-'+filterValue : '') + "." + this.format));
},
// Callback function of ajax request for custom result transformation
transform: function(res) {
return res;
}
},
/* Remote tiles served by a tile server, see http://en.wikipedia.org/wiki/Tile_Map_Service
* OSM Mapnik is the default server, see http://wiki.openstreetmap.org/wiki/Tile_servers
*/
tileserver: {
// Template of the domain (ie. {s} will be replaced by a, b, c, ...)
domain: 'http://{s}.tile.openstreetmap.org',
// Template of the path to image (ie. xyz will be replaced by integers)
path: '/{z}/{x}/{y}.png',
// URL generator
url: function() {
return this.domain + this.path;
}
}
};
}
/*
* Map configuration complete structure:
*
* - geoSources [object]
* - file [object]
* - domain [string]
* - path [string]
* - format [string]
* - url [string] function ( [string], [string], [string | int] )
* - transform [array] function ( [mixed] )
* - tileserver [object]
* - domain [string]
* - path [string]
* - url [string] function ( )
*/
;if (mapConfig) {
// Known types of geolayers with global setting inherited to geolayers with 'type' parameter
mapConfig.geoTypes = {
/* Tile type served by a tile map service (defined in geoSources)
* See http://leafletjs.com/reference.html#tilelayer
*/
tile: {
// Enable or not
active: true,
// Default source is a tile server defined in geoSources
source: 'tileserver',
// Same options supported by Leaflet API: http://leafletjs.com/reference.html#tilelayer-options
options: {
attribution: '',
opacity: 0.7
}
},
// Vector shapefile for thematic maps
thematic: {
// Enable or not
active: true,
// Binning algorithm, see https://github.com/simogeo/geostats (Classification)
// Supported names are the same of geostats functions without 'get' prefix
// It can be also an array of bounds for manually class definition
// Default value is 'Jenks'
classification: 'Jenks',
// Infowindow on click can be disabled
infowindow: true,
// Tooltip on mouseover can be disabled
tooltip: true,
// Fixed zoom on display
// If missing or zero, there is no restriction on zoom control
zoom: 0,
/* Layer style, with three presets:
* - default
* - highlight
* - selected
* Attributes defined in the latest two override default settings
* See http://leafletjs.com/reference.html#geojson-options
*/
style: {
// Default (on loading and reset)
default: {
weight: 0.5,
opacity: 1,
color: 'white',
fillOpacity: 0.7,
fillColor: 'none'
},
// Highlight (on mouseover)
highlight: {},
// Selected (on click)
selected: {
weight: 2,
color: '#666'
}
}
}
};
}
/*
* Map configuration complete structure:
*
* - geoTypes [object]
* - tile [object]
* - active [bool]
* - source [string matching geoSources attributes]
* - options [object matching http://leafletjs.com/reference.html#tilelayer-options structure]
* - thematic [object]
* - active [bool]
* - classification [string]
* - infowindow [bool]
* - tooltip [bool]
* - zoom [int>0]
* - style [object]
* - default [object matching http://leafletjs.com/reference.html#geojson-options style structure]
* - highlight [object]
* - selected [object]
*/
;if (mapConfig) {
// Known types of visualization into the infowindow with global setting inherited to infowindow with 'view' parameter
mapConfig.viewTypes = {
/* The infowindow contains a table with header and footer,
* here a structure of the body can be defined
* returning the tbody element, see http://www.w3schools.com/tags/tag_tbody.asp
*/
table: function(data, options, formatter, groups) {
if (!data) return '';
if (mapConfig.debug) console.log('views',arguments);
/* Default options can be overrided (include and exclude filters are evaluated in this order):
* - formatter string defines how to format numbers in printing
* - include array has data keys to include
* - exclude array has data keys to exclude
* - bold function defines a rule to boldify a row
* - filter function defines a custom filter after include and exclude filters
*/
var defaultOptions = {
include: [],
exclude: [],
bold: function(k,v) { return false; },
filter: function(k,v) { return true; },
},
options = options || {},
group = '',
tbody = '',
k, g = 0;
_.defaults(options, defaultOptions);
options.groups = groups || {};
options.formatter = formatter || function(k,v) { return (_.isNumber(v) ? (d3.format(",d")(v) || d3.format(",.2f")(v)) : v); };
for (k in data) {
if (_.has(data,k)) {
if (!options.include.length || _.contains(options.include,k)) {
if (!options.exclude.length || !(_.contains(options.exclude,k))) {
if (options.filter(k,data[k])) {
var val = options.formatter(k,data[k]),
isBold = options.bold(k,data[k]),
isSecondLevel = _.has(options.groups,k);
if (isSecondLevel && options.groups[k] != group) {
g++;
group = options.groups[k];
tbody += '<tr class="first-level group g'+g+'"><td colspan="2"><span>'+group+'</span></td></tr>';
}
tbody += '<tr class="'+(isSecondLevel ? 'second-level hidden g'+g : 'first-level')+'">' +
'<td class="table-key"><span>' + (isBold ? '<b>'+k+'</b>' : k) + '</span></td>' +
'<td class="table-value"><span>' + (isBold ? '<b>'+val+'</b>' : val) + '</span></td>' +
'</tr>';
}
}
}
}
}
return tbody;
}
};
}
/*
* Map configuration complete structure:
*
* - viewTypes [object]
* - table [string] function ( [object], [object] )
*/
;(function($) {
console.log("mapConfig",mapConfig);
if (!$) {
throw 'ERRORE: configurazione errata o mancante...';
return;
}
d3.geojson = d3.topojson = d3.json;
head.ready(function() {
// Global variables
var $ = mapConfig, // Configuration object
svgViewBox,
h, i, j, k,
selectedLayer;
/*** Language formatter ***/
if (_.has($,'language')) {
var myFormat;
switch($.language) {
case 'it':
myFormat = d3.locale({
"decimal": ",",
"thousands": ".",
"grouping": [3],
"currency": ["€ ", ""],
"dateTime": "%a %b %e %X %Y",
"date": "%d/%m/%Y",
"time": "%H:%M:%S",
"periods": ["AM", "PM"],
"days": ["Domenica", "Lunedì", "Martedì", "Mercoledì", "Giovedì", "Venerdì", "Sabato"],
"shortDays": ["Dom", "Lun", "Mar", "Mer", "Gio", "Ven", "Sab"],
"months": ["Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre"],
"shortMonths": ["Gen", "Feb", "Mar", "Apr", "Mag", "Giu", "Lug", "Ago", "Set", "Ott", "Nov", "Dic"]
});
break;
default:
myFormat = d3.locale();
}
d3.format = myFormat.numberFormat;
d3.time.format = myFormat.timeFormat;
}
/*** ***/
/*** Google Analytics ***/
if (_.has($,'analytics') && $.analytics.active) {
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', $.analytics.ua || '', 'auto');
ga('send', 'pageview');
}
/*** ***/
/*** Configuration initialization ***/
// Geolayers
for (i=0; i<$.geoLayers.length; i++) {
// Opzioni di default
if (_.has($.geoTypes[$.geoLayers[i].type],'options')) {
$.geoLayers[i].options = $.geoLayers[i].options || {};
_.defaults($.geoLayers[i].options, $.geoTypes[$.geoLayers[i].type].options);
}
// Stili di default
if (_.has($.geoTypes[$.geoLayers[i].type],'style')) {
$.geoLayers[i].style = $.geoLayers[i].style || { default: {}, highlight: {}, selected: {} };
_.defaults($.geoLayers[i].style.default, $.geoTypes[$.geoLayers[i].type].style.default);
_.defaults($.geoLayers[i].style.highlight, $.geoTypes[$.geoLayers[i].type].style.highlight);
_.defaults($.geoLayers[i].style.selected, $.geoTypes[$.geoLayers[i].type].style.selected);
}
// Parametri di default per il geoType
_.defaults($.geoLayers[i], $.geoTypes[$.geoLayers[i].type]);
// Parametri di default per il geoSource
_.defaults($.geoLayers[i], $.geoSources[$.geoLayers[i].source]);
}
// Filtra via i geoLayer non attivi
$.geoLayers = _.where($.geoLayers, {active: true});
// Datasets
for (i=0; i<$.dataSets.length; i++) {
// Parametri di default per il dataType
_.defaults($.dataSets[i], $.dataTypes[$.dataSets[i].type]);
// Parametri di default per il dataSource
_.defaults($.dataSets[i], $.dataSources[$.dataSets[i].source]);
}
// Ignore datasets linked to disabled geolayers
$.dataSets = _.filter($.dataSets, function(el) {
return (_.has(el,'schema') && _.has(el.schema,'layer') && _.contains(_.map($.geoLayers, function(l) {
return (_.has(l,'schema') ? l.schema.name : undefined);
}), el.schema.layer));
});
// Downloads in infowindow
if (_.has($,'infowindow') && $.infowindow.active && _.has($.infowindow,'downloads') && $.infowindow.downloads.active) {
for (i=0; i<$.infowindow.downloads.files.length; i++) {
if ($.infowindow.downloads.files[i].active) {
_.defaults($.infowindow.downloads.files[i], $.dataSources[$.infowindow.downloads.files[i].source]);
}
}
}
// PointsSet
if (_.has($,'pointsSet') && $.pointsSet.active) {
_.defaults($.pointsSet, $.dataSources[$.pointsSet.source]);
}
if ($.debug) console.log("$",$);
/*** ***/
/*** Url shortener initialization ***/
var dtnj; // URL shortener via yourls-api lib
if (_.has($,'urlShortener') && $.urlShortener.active) {
dtnj = yourls.connect($.urlShortener.url.call($.urlShortener), { signature: $.urlShortener.signature });
}
if ($.debug) console.log("dtnj",dtnj);
/*** ***/
/*** Geo layers initialization ***/
var defaultGeo = {}, geo = {}; // Geo layers enabled and used
for (i=0; i<$.geoLayers.length; i++) {
if ($.geoLayers[i].type === 'thematic') {
defaultGeo[$.geoLayers[i].schema.name] = {
id: $.geoLayers[i].schema.id,
label: $.geoLayers[i].schema.label,
resource: [],
list: []
};
}
}
if ($.debug) console.log("defaultGeo",defaultGeo);
/*** Data sets initialization ***/
var defaultData = {}, data = {}; // Data sets enabled and used
for (i=0; i<$.dataSets.length; i++) {
var dataSet = $.dataSets[i];
defaultData[dataSet.schema.name] = {
name: dataSet.schema.name || _.uniqueId('dataset-'),
layer: dataSet.schema.layer,
id: (dataSet.source != 'shape' ? dataSet.schema.id || undefined : undefined),
groups: {},
columns: (_.has(dataSet.schema,'menu') && dataSet.schema.menu.length ? dataSet.schema.menu.map(function(el) { return el.column; }) : null),
labels: (_.has(dataSet.schema,'menu') && dataSet.schema.menu.length ? dataSet.schema.menu.map(function(el) { return el.label || el.column; }) : null),
descriptions: (_.has(dataSet.schema,'menu') && dataSet.schema.menu.length ? dataSet.schema.menu.map(function(el) { return el.description || dataSet.schema.description || (el.label ? el.label + '>' + el.column : el.column); }) : null),
precisions: (_.has(dataSet.schema,'menu') && dataSet.schema.menu.length ? dataSet.schema.menu.map(function(el) { return _.isNumber(el.precision) ? el.precision : (dataSet.precision || 0); }) : null),
resourceId: dataSet.resourceId, // HMMM
palette: dataSet.palette || 'Reds',
transform: dataSet.transform || function(k,v) { return v; },
resource: [],
binsNums: (_.has(dataSet.schema,'menu') && dataSet.schema.menu.length ? dataSet.schema.menu.map(function(el) { return el.bins || dataSet.bins; }) : null),
bins: [],
ranges: [],
active: false
};
defaultData[dataSet.schema.name].menuLabel = dataSet.schema.label || defaultData[dataSet.schema.name].name;
defaultData[dataSet.schema.name].column = defaultData[dataSet.schema.name].columns[0];
defaultData[dataSet.schema.name].label = defaultData[dataSet.schema.name].labels[0];
defaultData[dataSet.schema.name].description = defaultData[dataSet.schema.name].descriptions[0];
defaultData[dataSet.schema.name].precision = defaultData[dataSet.schema.name].precisions[0];
defaultData[dataSet.schema.name].binsNum = defaultData[dataSet.schema.name].binsNums[0];
// Columns grouping
if (_.has(dataSet.schema,'groups') && !_.isEmpty(dataSet.schema.groups)) {
for (k in dataSet.schema.groups) {
if (_.has(dataSet.schema.groups,k) && !_.isEmpty(dataSet.schema.groups[k])) {
_.each(dataSet.schema.groups[k], function(el) {
defaultData[dataSet.schema.name].groups[el] = k;
});
}
}
}
// Parsing function for dataset columns
if (_.isString(dataSet.parse)) {
var parseFn = window[dataSet.parse];
defaultData[dataSet.schema.name].parse = function(k,v) { var val = parseFn(v); return _.isNumber(val) && !_.isNaN(val) ? val : v; };
} else if (_.isFunction(dataSet.parse)) {
defaultData[dataSet.schema.name].parse = dataSet.parse;
} else {
defaultData[dataSet.schema.name].parse = function(k,v) { var val = parseFloat(v); return _.isNumber(val) && !_.isNaN(val) ? val : v; };
}
// Formatter function for dataset columns
if (_.isString(dataSet.formatter) && !_.isEmpty(dataSet.formatter)) {
defaultData[dataSet.schema.name].formatter = function(k,v) {
return d3.format(dataSet.formatter)(v);
};
} else if (_.isFunction(dataSet.formatter)) {
(function(i) {
var dataSet = $.dataSets[i];
defaultData[dataSet.schema.name].formatter = function(k,v) {
var formatter = dataSet.formatter(k,v);
if (formatter) {
return d3.format(formatter)(v);
} else {
return (_.isNumber(v) ? (d3.format(",d")(v) || d3.format(",.2f")(v)) : v);
}
};
})(i);
} else {
defaultData[dataSet.schema.name].formatter = function(k,v) {
return (_.isNumber(v) ? (d3.format(",d")(v) || d3.format(",.2f")(v)) : v);
};
}
}
if ($.debug) console.log("defaultData",defaultData);
/*** ***/
/*** URL GET parameters initialization ***/
var parameters = Arg.query(); // Parsing URL GET parameters
/* ie. http://viz.confiscatibene.it/anbsc/choropleth/?ls[0]=regioni&ls[1]=province&ls[2]=comuni&dl=regioni&t=1
{
ls: Array(), // Livelli caricati: regioni, province, comuni (default: tutti) -- LAYERS
md: [string], // Layout di visualizzazione: full (default), embed, widget (auto se su mobile) -- MODE
dl: [string], // Livello mostrato al caricamento -- DEFAULT LAYER
ml: [string], // Livello caricato più alto: regioni, province, comuni -- MAX LAYER
tl: [string], // Livello a cui si riferisce t -- TERRITORY LAYER
t: [int], // Codice istat del territorio centrato e con infowindow aperta (si riferisce a tl) -- TERRITORY
i: [int] // Codice istat del territotio con infowindow aperta -- INFO,
summary: [bool] // Se attiva, permette di nascondere la barra laterale
}
*/
parameters.ls = parameters.ls || d3.keys(defaultGeo); // Livelli caricati (default: tutti)
parameters.ml = parameters.ls[0]; // Livello caricato più alto (PRIVATO)
parameters.dl = parameters.dl || parameters.ml; // Livello visibile al caricamento
parameters.md = parameters.md || (L.Browser.mobile && head.screen.innerWidth < 800 ? 'widget' : ''); // Layout
d3.select('body').classed(parameters.md,true); // Tengo traccia del layout come classe del body
if (parameters.t) { // Focus su un region (codice istat che si riferisce a tl)
parameters.tl = parameters.tl || parameters.ml; // Livello a cui si riferisce t
parameters.ml = parameters.ls[_.indexOf(parameters.ls,parameters.tl)+1]; // Si riferisce ora al livello più alto caricato
if (_.indexOf(parameters.ls,parameters.dl) < _.indexOf(parameters.ls,parameters.tl)+1) {
parameters.dl = parameters.ml;
}
}
if (_.has($,'pointsSet') && $.pointsSet.active && parameters.mr && _.has(parameters.mr,'rid')) {
$.pointsSet.resourceId = parameters.mr.rid;
parameters.mr.lat = parameters.mr.lat || 'lat';
parameters.mr.lng = parameters.mr.lng || 'lng';
}
if (_.has($,'summary') && !_.isUndefined(parameters.summary)) {
$.summary.closed = !parameters.summary;
}
if ($.debug) console.log("parameters",parameters);
// Livelli disponibili da parametri dell'URL
for (i=_.indexOf(parameters.ls,parameters.ml); i<parameters.ls.length; i++) {
if (_.has(defaultGeo,parameters.ls[i])) {
var defaultJoinData = [];
for (k in defaultData) {
if (_.has(defaultData,k) && defaultData[k].layer === parameters.ls[i]) {
defaultJoinData.push(defaultData[k]);
}
}
if (defaultJoinData.length) {
geo[parameters.ls[i]] = defaultGeo[parameters.ls[i]];
data[parameters.ls[i]] = _.each(defaultJoinData, function(el,index) { el.index = index; });
}
}
}
if ($.debug) console.log("geo",geo);
if ($.debug) console.log("data",data);
/*** ***/
/*** Inizializzazione della mappa ***/
var map,
southWest,
northEast,
mapBounds,
southWestB,
northEastB,
maxMapBounds;
if (_.has($.map,'bounds')) {
if (_.has($.map.bounds,'init')) {
southWest = L.latLng($.map.bounds.init.southWest);
northEast = L.latLng($.map.bounds.init.northEast);
mapBounds = L.latLngBounds(southWest, northEast);
}
if (_.has($.map.bounds,'max')) {
southWestB = L.latLng($.map.bounds.max.southWest);
northEastB = L.latLng($.map.bounds.max.northEast);
maxMapBounds = L.latLngBounds(southWestB, northEastB);
}
}
map = L.map('map', {
maxZoom: $.map.zoom.max || null,
minZoom: $.map.zoom.min || null,
zoom: (parameters.md != 'widget' ? $.map.zoom.init : $.map.zoom.init-1) || null,
center: ($.map.center || (mapBounds ? mapBounds.getCenter() : null)),
scrollWheelZoom: (_.has($.map.zoom,'scrollWheel') ? $.map.zoom.scrollWheel : true),
attributionControl: !$.map.attribution.length,
maxBounds: maxMapBounds || null
});
if (!$.map.zoom.init && mapBounds) map.fitBounds(mapBounds);
if ($.debug) console.log("map",map);
// Tile layers
var tileLayers = $.geoLayers.filter(function(l) { return l.type === 'tile'; });
if ($.debug) console.log("tileLayers",tileLayers);
for (i=0; i<tileLayers.length; i++) {
L.tileLayer(tileLayers[i].url.call(tileLayers[i]), tileLayers[i].options).addTo(map);
}
// Attribution notices
var attrib = L.control.attribution();
for (i=0; i<$.map.attribution.length; i++) {
attrib.addAttribution($.map.attribution[i]);
}
if ($.debug) console.log("attrib",attrib);
attrib.addTo(map);
/*** ***/
/*** Gestione dell'infowindow al click ***/
var info;
if (_.has($,'infowindow') && $.infowindow.active) {
if (parameters.md === 'widget') {
info = {
_div: d3.select('body').append('div').attr("class", "info bottom").node(),
addTo: function(map) { this.onAdd(map); return this; }
};
} else if (_.has($.infowindow,'position') && $.infowindow.position != 'inside') {
info = {};
d3.select('body').classed('summary '+$.infowindow.position, true);
if ($.infowindow.position === 'top' || $.infowindow.position === 'left') {
info._div = d3.select('body').insert('div','#map').attr("class", "info external "+$.infowindow.position).node();
} else if ($.infowindow.position === 'right' || $.infowindow.position === 'bottom') {
info._div = d3.select('body').append('div').attr("class", "info external "+$.infowindow.position).node();
}
info.addTo = function(map) {
this.onAdd(map);
return this;
};
} else {
info = L.control({position: 'bottomright'});
}
info.onAdd = function (map) {
this._div = this._div || L.DomUtil.create('div', 'info '+parameters.md);
d3.select(this._div)
.attr('id','infowindow')
.style('max-height', (parameters.md != 'widget' ? (head.screen.innerHeight-100)+'px' : null))
.classed('empty', function() {
return parameters.md === 'widget' ? !(_.has($.infowindow.content,'mobile') && $.infowindow.content.mobile) : !(_.has($.infowindow.content,'default') && $.infowindow.content.default);
})
.on("mouseenter", function() {
map.scrollWheelZoom.disable();
map.doubleClickZoom.disable();
})
.on("mouseleave", function() {
if (_.has($.map.zoom,'scrollWheel') && $.map.zoom.scrollWheel) map.scrollWheelZoom.enable();
map.doubleClickZoom.enable();
});
this.update();
return this._div;
};
info.update = function (props) {
var that = this;
this._div.innerHTML = '';
if (props) {
d3.select(this._div)
.classed("closed", false)
.classed("empty", false);
if (parameters.md === 'widget') map.dragging.disable();
var delim = agnes.rowDelimiter(),
today = new Date(),
stoday = d3.time.format('%Y%m%d')(today),
region = props._layer,
dataSet = data[region].filter(function(el) { return el.active; })[0],
filterKey = dataSet.id,
filterValue = props[geo[region].id],
buttons = [], btnTitle, btnUrl, btnPlace,
dnlBtn = [],
globalImagePath = (_.isString($.infowindow.path) ? $.infowindow.path : 'icons/');
if (_.has($.infowindow,'shareButtons') && $.infowindow.shareButtons.active) {
var shareImagePath = (_.isString($.infowindow.shareButtons.path) ? $.infowindow.shareButtons.path : globalImagePath);
btnTitle = $.infowindow.shareButtons.title + (region == 'regioni' ? ' in ' : ' a ') + props[geo[region].label];
btnUrl = 'http://' + location.hostname + Arg.url(parameters).replace(/&*md=[^&]*/,'').replace(/&{2,}/g,"&");
btnEncUrl = 'http://' + location.hostname + encodeURIComponent(Arg.url(parameters).replace(/&*md=[^&]*/,'').replace(/&{2,}/g,"&"));
btnPlace = props[geo[region].label];
if ($.infowindow.shareButtons.url) {
btnUrl = btnEncUrl = $.infowindow.shareButtons.url;
}
if (_.has($.infowindow.shareButtons,'twitter') && $.infowindow.shareButtons.twitter.active) {
buttons.push('<a class="ssb" href="http://twitter.com/share?url=' + btnEncUrl +
'&via=' + $.infowindow.shareButtons.twitter.via +
'&text=' +
encodeURIComponent((_.isFunction($.infowindow.shareButtons.twitter.text) ? $.infowindow.shareButtons.twitter.text(props._data[dataSet.name]) : btnPlace + ' - ' + $.infowindow.shareButtons.twitter.text)) +
'" target="_blank" title="'+btnTitle+' su Twitter"><img src="'+shareImagePath+($.infowindow.shareButtons.twitter.image || 'twitter.png')+'" id="ssb-twitter"></a>'
);
}
if (_.has($.infowindow.shareButtons,'facebook') && $.infowindow.shareButtons.facebook.active) {
buttons.push('<a class="ssb" href="http://www.facebook.com/sharer.php?u=' + btnEncUrl +
'" target="_blank" title="'+btnTitle+' su Facebook"><img src="'+shareImagePath+($.infowindow.shareButtons.facebook.image || 'facebook.png')+'" id="ssb-facebook"></a>'
);
}
if (_.has($.infowindow.shareButtons,'gplus') && $.infowindow.shareButtons.gplus.active) {
buttons.push('<a class="ssb" href="https://plus.google.com/share?url=' + btnEncUrl +
'" target="_blank" title="'+btnTitle+' su Google Plus"><img src="'+shareImagePath+($.infowindow.shareButtons.gplus.image || 'gplus.png')+'" id="ssb-gplus"></a>'
);
}
if (_.has($.infowindow.shareButtons,'linkedin') && $.infowindow.shareButtons.linkedin.active) {
buttons.push('<a class="ssb" href="http://www.linkedin.com/shareArticle?mini=true&url=' + btnEncUrl +
'" target="_blank" title="'+btnTitle+' su LinkedIn"><img src="'+shareImagePath+($.infowindow.shareButtons.linkedin.image || 'linkedin.png')+'" id="ssb-linkedin"></a>'
);
}
if (_.has($.infowindow.shareButtons,'email') && $.infowindow.shareButtons.email.active) {
buttons.push('<a class="ssb" href="mailto:?Subject=' + encodeURIComponent((_.isFunction($.infowindow.shareButtons.email.subject) ? $.infowindow.shareButtons.email.subject(props._data[dataSet.name]) : $.infowindow.shareButtons.email.subject + ' | ' + btnPlace)) +
'&Body=' + encodeURIComponent((_.isFunction($.infowindow.shareButtons.email.body) ? $.infowindow.shareButtons.email.body(props._data[dataSet.name],btnEncUrl) : btnPlace + ' - ' + $.infowindow.shareButtons.email.body + ': ' + btnUrl)) +
'" target="_blank" title="'+btnTitle+' per email"><img src="'+shareImagePath+($.infowindow.shareButtons.email.image || 'email.png')+'" id="ssb-email"></a>'
);
}
if (_.has($.infowindow.shareButtons,'permalink') && $.infowindow.shareButtons.permalink.active) {
buttons.push('<a class="ssb" href="' + btnUrl +
'" target="_blank" title="Permalink"><img src="'+shareImagePath+($.infowindow.shareButtons.permalink.image || 'link.png')+'" id="ssb-link"></a>'
);
}
}
if ($.debug) console.log("shareButtons",buttons);
if (_.has($.infowindow,'downloads') && $.infowindow.downloads.active) {
var dwnlImagePath = (_.isString($.infowindow.downloads.path) ? $.infowindow.downloads.path : globalImagePath);
for (i=0; i<$.infowindow.downloads.files.length; i++) {
if ($.infowindow.downloads.files[i].active) {
if (!$.infowindow.downloads.files[i].datasets || !$.infowindow.downloads.files[i].datasets.length || _.contains($.infowindow.downloads.files[i].datasets,dataSet.name)) {
dnlBtn.push('<a id="a-' +
$.infowindow.downloads.files[i].name +
'" class="dnl" href="'+($.infowindow.downloads.files[i].filename ? $.infowindow.downloads.files[i].url() : '#')+'" title="' +
$.infowindow.downloads.files[i].title +
'"><img src="' +
dwnlImagePath + ($.infowindow.downloads.files[i].image || $.infowindow.downloads.image || 'download.png') +
'" /></a>'
);
}
}
}
}
if ($.debug) console.log("downloadButtons",dnlBtn);
var thead = '<thead>' +
'<tr>' +
'<th colspan="2">' +
(dnlBtn.length ? '<span id="sdnlBtn">'+dnlBtn.join(" ")+'</span>' + ' ' : '') +
(buttons.length ? '<span id="sshrBtn">'+buttons.join(" ")+'</span>' : '') +
'<a id="close-cross" href="#" title="Chiudi"><img src="'+globalImagePath+($.infowindow.image || 'close.png')+'" /></a>' +
'</th>' +
'</tr>' +
(geo[region].label ? '<tr>' +
'<th colspan="2" class="rossobc">' + props[geo[region].label] + '</th>' +
'</tr>' : '') +
'</thead>';
//if ($.debug) console.log("Table header",thead);
var tfoot;
if (_.has($.infowindow,'downloads') && $.infowindow.downloads.active) {
tfoot = '<tfoot>' +
'<tr><td colspan="2" style="text-align:right;font-size: smaller;">' +
($.infowindow.downloads.license || '') +
'</td></tr>' +
'</tfoot>';
} else {
tfoot = '<tfoot></tfoot>';
}
//if ($.debug) console.log("Table footer",tfoot);
var tbody;
if (_.has($.infowindow,'view') && $.infowindow.view.active && _.has($.viewTypes,$.infowindow.view.type)) {
tbody = $.viewTypes[$.infowindow.view.type](props._data[dataSet.name], $.infowindow.view.options, dataSet.formatter, dataSet.groups);
if (!(tbody.search('<tbody>') > -1)) {
tbody = '<tbody>' + tbody + '</tbody>';
}
} else {
tbody = '<tbody></tbody>';
}
//if ($.debug) console.log("Table body",tbody);
this._div.innerHTML += '<table class="zebra">' + thead + tbody + tfoot + '</table>';
//if ($.debug) console.log("Table", this._div.innerHTML);
d3.selectAll("tr.first-level.group")
.on("click", function(d,i) {
d3.select(this)
.classed("open", !d3.select(this).classed("open"));
d3.selectAll("tr.second-level.g"+(i+1)).classed("hidden", function() { return !d3.select(this).classed("hidden"); });
});
if (_.has($.infowindow,'shareButtons') && $.infowindow.shareButtons.active && _.has($,'urlShortener') && $.urlShortener.active) {
dtnj.shorten(btnEncUrl, $.urlShortener.prefix+md5(btnUrl), function(data) {
var btnEncUrl = data.shorturl,
buttons = [];
if (_.has($.infowindow.shareButtons,'twitter') && $.infowindow.shareButtons.twitter.active) {
buttons.push('<a class="ssb" href="http://twitter.com/share?url=' + btnEncUrl +
'&via=' + $.infowindow.shareButtons.twitter.via +
'&text=' + encodeURIComponent(btnPlace + ' - ' + $.infowindow.shareButtons.twitter.text + ' ') +
'" target="_blank" title="'+btnTitle+' su Twitter"><img src="'+imagePath+($.infowindow.shareButtons.twitter.image || 'twitter.png')+'" id="ssb-twitter"></a>'
);
}
if (_.has($.infowindow.shareButtons,'facebook') && $.infowindow.shareButtons.facebook.active) {
buttons.push('<a class="ssb" href="http://www.facebook.com/sharer.php?u=' + btnEncUrl +
'" target="_blank" title="'+btnTitle+' su Facebook"><img src="'+imagePath+($.infowindow.shareButtons.facebook.image || 'facebook.png')+'" id="ssb-facebook"></a>'
);
}
if (_.has($.infowindow.shareButtons,'gplus') && $.infowindow.shareButtons.gplus.active) {
buttons.push('<a class="ssb" href="https://plus.google.com/share?url=' + btnEncUrl +
'" target="_blank" title="'+btnTitle+' su Google Plus"><img src="'+imagePath+($.infowindow.shareButtons.gplus.image || 'gplus.png')+'" id="ssb-gplus"></a>'
);
}
if (_.has($.infowindow.shareButtons,'linkedin') && $.infowindow.shareButtons.linkedin.active) {
buttons.push('<a class="ssb" href="http://www.linkedin.com/shareArticle?mini=true&url=' + btnEncUrl +
'" target="_blank" title="'+btnTitle+' su LinkedIn"><img src="'+imagePath+($.infowindow.shareButtons.linkedin.image || 'linkedin.png')+'" id="ssb-linkedin"></a>'
);
}
if (_.has($.infowindow.shareButtons,'email') && $.infowindow.shareButtons.email.active) {
buttons.push('<a class="ssb" href="mailto:?Subject=' + encodeURIComponent($.infowindow.shareButtons.email.subject + ' | ' + btnPlace) +
'&Body=' + encodeURIComponent(btnPlace + ' - ' + $.infowindow.shareButtons.email.body + ': ') + btnEncUrl +
'" target="_blank" title="'+btnTitle+' per email"><img src="'+imagePath+($.infowindow.shareButtons.email.image || 'email.png')+'" id="ssb-email"></a>'
);
}
if (_.has($.infowindow.shareButtons,'permalink') && $.infowindow.shareButtons.permalink.active) {
buttons.push('<a class="ssb" href="' + btnUrl +
'" target="_blank" title="Permalink"><img src="'+imagePath+($.infowindow.shareButtons.permalink.image || 'link.png')+'" id="ssb-link"></a>'
);
}
d3.select("#sshrBtn").node().innerHTML = buttons.join(" ");
});
}
if (_.has($.infowindow,'downloads') && $.infowindow.downloads.active) {
for (i=0; i<$.infowindow.downloads.files.length; i++) {
if ($.infowindow.downloads.files[i].active && !$.infowindow.downloads.files[i].filename) {
(function(i) {
var dnlPath = $.infowindow.downloads.files[i].url.call($.infowindow.downloads.files[i], region, filterKey, filterValue);
var dnlFile = stoday +
'_' + $.infowindow.downloads.files[i].filebase +
'-' + $.infowindow.downloads.files[i].name +