-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmap.js
More file actions
878 lines (811 loc) · 28.1 KB
/
map.js
File metadata and controls
878 lines (811 loc) · 28.1 KB
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
(function ($) {
$.fn.envmap = function(settings) {
window.userPos = [];
var init = 0;
var o = $.extend({
"factory": "data/factory.js",
"factoryPopupLoading": "Loading ...",
"factoryPopupCallback": "",
"factoryPopupLoading": "",
"twCounty": "data/twCounty2010.json",
"airquality": "data/airquality.json",
"airbox": "data/airbox.json",
"airboxPopupCallback": "",
"formBinding": '',
"mapid": ''
}, settings);
var current = this;
var started = false;
$.ajaxSetup({ cache: true });
// global vars
var mapopt = {
"latlng": [24.292754, 120.653797],
"zoom": 10,
"basemap": 'satellite',
"factory":{
"id": '',
"address": '',
"name": '',
"enabled" : 1,
"type": 'All',
"poltype": 'All',
"fine": 1,
"finehard": 0,
"realtime": 0,
"illegal": 0,
"overhead": 0
},
"airquality": {
"enabled": 1
},
"airbox": {
"id": '',
"enabled": 1
}
};
var mapid = o.mapid;
var maplayers = {};
window.colorPlate = function(type, v){
var colorplateAQI = ['#00E800','#FFFF00','#ff7e00','#ff0000','#8f3f97','#7e0023'];
var colorplatePm25= ['#9CFF9C','#31FF00','#31CF00','#FFFF00','#FFCF00','#FF9A00','#FF6464','#FF0000','#990000','#CE30FF'];
var color = 0;
if(type == 'pm25'){
if(v > 70) { color = 9; }
else if(v >= 65) { color = 8; }
else if(v >= 59) { color = 7; }
else if(v >= 54) { color = 6; }
else if(v >= 48) { color = 5; }
else if(v >= 42) { color = 4; }
else if(v >= 36) { color = 3; }
else if(v >= 24) { color = 2; }
else if(v >= 12) { color = 1; }
return colorplatePm25[color];
}
if(type == 'AQI'){
if(v > 300) { color = 5; }
else if(v > 200 ) { color = 4; }
else if(v > 150 ) { color = 3; }
else if(v > 100 ) { color = 2; }
else if(v > 50) { color = 1; }
else {
color = 0;
}
return colorplateAQI[color];
}
}
var geocodeAddress = function(address, callback) {
if (typeof google === 'undefined' || !google.maps || !google.maps.Geocoder) {
console.error('Google Maps API not loaded');
callback(null);
return;
}
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': address}, function(results, status) {
console.log('Map API triggered: '+status);
if (status === 'OK' && results.length > 0) {
var location = results[0].geometry.location;
var lat = location.lat();
var lng = location.lng();
// Check if coordinates are within Taiwan and coastal areas
if (isInTaiwan(lat, lng)) {
callback({lat: lat, lng: lng});
} else {
callback(null);
}
} else {
callback(null);
}
});
};
var isInTaiwan = function(lat, lng) {
// Taiwan boundary coordinates (approximate)
// Including main island and offshore areas
var taiwanBounds = {
north: 26.5,
south: 21.5,
east: 122.5,
west: 118.0
};
return (lat >= taiwanBounds.south && lat <= taiwanBounds.north &&
lng >= taiwanBounds.west && lng <= taiwanBounds.east);
};
var layerSearch = function(map){
const taiwanCoordinates = {
"基隆": {"lat": 25.128297, "lng": 121.739213},
"新北": {"lat": 25.0622095, "lng": 121.4570447},
"桃園": {"lat": 24.9925185, "lng": 121.305975},
"新竹": {"lat": 24.8138287, "lng": 120.9674798},
"苗栗": {"lat": 24.560159, "lng": 120.8214265},
"臺中": {"lat": 24.1629765, "lng": 120.6746104},
"彰化": {"lat": 24.0716583, "lng": 120.5624474},
"雲林": {"lat": 23.7092033, "lng": 120.4313373},
"南投": {"lat": 23.9609981, "lng": 120.9718638},
"嘉義": {"lat": 23.4800751, "lng": 120.4491113},
"臺南": {"lat": 22.9994761, "lng": 120.2292723},
"高雄": {"lat": 22.6272772, "lng": 120.3014375},
"屏東": {"lat": 22.672814, "lng": 120.4957408},
"宜蘭": {"lat": 24.7021073, "lng": 121.7377502},
"花蓮": {"lat": 23.9910732, "lng": 121.6111949},
"臺東": {"lat": 22.761315, "lng": 121.1439117},
"澎湖": {"lat": 23.5711899, "lng": 119.5793157},
"金門": {"lat": 24.3487791, "lng": 118.3285644},
"連江": {"lat": 26.1975299, "lng": 119.53957}
};
let city = mapopt.factory.address;
console.log(city);
let coord = taiwanCoordinates[city] || null;
console.log(coord);
if (coord) {
map.panTo(coord);
}
}
var layerOsm = function(map){
// osm tile
maplayers.osm = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
"zIndex": 10,
"attribution": '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
});
if(mapopt.basemap != 'street'){
return;
}
if(typeof map != 'undefined'){
map.addLayer(maplayers.osm);
}
}
var layerSatellite = function(map){
var maxZoom = 17;
//var tileOpt = {"tms": true, "maxZoom": maxZoom, "zIndex": 11};
maplayers.satellite = L.layerGroup();
if(mapopt.basemap != 'satellite'){
return;
}
var url='https://wmts.nlsc.gov.tw/wmts';
maplayers.satellite.addLayer(new L.TileLayer.WMTS( url , {
layer: 'PHOTO2',
style: "default",
tilematrixSet: "GoogleMapsCompatible",
format: "image/jpeg",
attribution: "<a href='https://github.com/mylen/leaflet.TileLayer.WMTS'>GitHub</a>© <a href='http://maps.nlsc.gov.tw'>NLSC</a>"
}));
if(typeof map != 'undefined'){
map.addLayer(maplayers.satellite);
}
}
var layerTWCounty = function(map){
if(mapopt.basemap !== 'satellite'){
return;
}
maplayers.twcounty = L.geoJson();
$.getJSON(o.twCounty, function(twgeojson){
maplayers.twcounty = L.geoJson(twgeojson, {
style: function(feature) {
return {
"weight": 3,
"color": "#EEE",
"opacity": 0.5,
"fillColor": "#000",
"fillOpacity": 0
};
}
});
maplayers.twcounty.setZIndex(10);
if(typeof map != 'undefined'){
map.addLayer(maplayers.twcounty);
}
});
}
var layerFactory = function(map){
var $progress = $('#progress');
var $progressBar = $('#progress-bar');
emptyResult(false);
maplayers.factory = L.markerClusterGroup({
chunkedLoading: true,
showCoverageOnHover: false,
spiderfyOnMaxZoom: true,
chunkProgress: function(processed, total, elapsed, layersArray){
if (elapsed > 100) {
// if it takes more than a second to load, display the progress bar:
$progress.css('display', 'block');
$progressBar.css('width', Math.round(processed/total*100) + '%');
}
if (processed >= total) {
// all markers processed - hide the progress bar:
setTimeout(function(){
$progress.hide();
formLoading(false);
}, 600);
}
}});
if(mapopt.factory.enabled && !map.hasLayer(maplayers.factory)){
var tokens = {
'{factory.type}': String(mapopt.factory.type).toLowerCase(),
'{factory.poltype}': String(mapopt.factory.poltype).toLowerCase(),
'{factory.fine}':mapopt.factory.fine ? 1 : 0,
'{factory.finehard}':mapopt.factory.finehard ? 1 : 0,
'{factory.realtime}':mapopt.factory.realtime ? 1 : 0,
'{factory.illegal}':mapopt.factory.illegal ? 1 : 0,
'{factory.overhead}':mapopt.factory.overhead ? mapopt.factory.overhead : 0,
'{factory.address}': String(mapopt.factory.address),
'{factory.name}': String(mapopt.factory.name)
};
var url = replaceToken(o.factory, tokens);
// Backup current markerList before new search
window.backupMarkerList = window.markerList ? window.markerList.slice() : [];
$.getScript(url, function(data, textStatus, jqxhr) {
window.markerList = [];
var selectedFactory;
for (var i = 0; i < factoryPoints.length; i++) {
if(!factoryPoints[i][2] || ! factoryPoints[i][3]) {
continue;
}
var factory = factoryPoints[i];
var title = factory[1];
var registrationNo = factory[0];
var icon = typeof factory[5] !== "undefined" && factory[5] > 0 ? 'industry' : factory[4] != '0' ? "exclamation-triangle" : "building";
var markerColor = typeof factory[5] !== "undefined" && factory[5] > 0 ? 'orange' : factory[4] != '0' ? "red" : "blue";
var amarker = L.AwesomeMarkers.icon({
"icon": icon,
"prefix": "fa",
"iconColor": "white",
"markerColor": markerColor
});
var marker = L.marker(L.latLng(factory[2], factory[3]), {
"title": title,
"icon": amarker
});
if(o.factoryPopupCallback && o.factoryPopupCallback.length){
marker.bindPopup(o.factoryPopupLoading);
(function(f){
marker.on('click', function(e){
mapopt.factory.id = f[0];
hashUpdate(mapopt);
//ga('send', 'event', 'map', 'click-marker', f[1]);
o.factoryPopupCallback(e, f);
});
marker.getPopup().on('remove', function() {
mapopt.factory.id = "";
hashUpdate(mapopt);
});
})(factory);
}
else{
marker.bindPopup(title + '<br>' + registrationNo);
}
window.markerList.push(marker);
if(mapopt.factory.id == registrationNo) {
selectedFactory = marker;
}
else if(mapopt.factory.name == title){
selectedFactory = marker;
}
}
if (window.markerList.length == 1) {
marker.fire('click').openPopup();
}
else if (window.markerList.length <= 0) {
if (window.backupMarkerList && window.backupMarkerList.length > 0) {
window.markerList = window.backupMarkerList.slice();
}
// No factory results found, try geocoding the search term as an address
var searchTerm = mapopt.factory.name || '';
if (searchTerm.length >= 8 && window.markerList.length > 1) {
geocodeAddress(searchTerm, function(coords) {
if (coords) {
// Move to geocoded location
mapobj.setView([coords.lat, coords.lng], 15);
formLoading(false);
// Don't show empty result since we found a location
} else {
// Geocoding failed, show empty result
formLoading(false);
emptyResult(true);
}
});
} else {
// Search term too short for geocoding
formLoading(false);
emptyResult(true);
}
}
maplayers.factory.addLayers(window.markerList);
maplayers.factory.setZIndex(20);
if (window.location.search.indexOf('qt-front_content') < 0 && mapopt.factory.id.length <= 0) {
if (window.userPos.length > 0 && !init) {
console.log('Use user location');
}
else{
map.fitBounds(maplayers.factory.getBounds());
}
}
init = 1;
if(typeof map != 'undefined'){
map.addLayer(maplayers.factory);
if (selectedFactory) {
map.fitBounds(maplayers.factory.getBounds());
setTimeout(function(){
maplayers.factory.zoomToShowLayer(selectedFactory, function () {
selectedFactory.fire('click');
});
}, 500);
}
}
});
}
else
if(!mapopt.factory.enabled && map.hasLayer(maplayers.factory)){
map.removeLayer(maplayers.factory);
}
}
var layerFactoryLabel = function(map){
maplayers.legend = L.control({'position':'topright'});
maplayers.legend.onAdd = function(map){
this._div = L.DomUtil.create('div', 'leaflet-custom-legend');
var html = '<div><div class="awesome-marker-icon-red awesome-marker" tabindex="0" style="position: static; width: 35px; height: 45px; display:inline-block"><i class="fa fa-exclamation-triangle icon-white" style="margin-top:10px"></i> </div>最近一個月或半年超標</div>';
html += '<div><div class="awesome-marker-icon-blue awesome-marker leaflet-zoom-animated" tabindex="0" style="position:static;width: 35px; height: 45px; display:inline-block;"><i class="fa fa-building icon-white" style="margin:10px 0 0 2px"></i> </div>未超標的單位</div>';
html += '<div><div class="awesome-marker-icon-orange awesome-marker leaflet-zoom-animated" tabindex="0" style="position:static;width: 35px; height: 45px; display:inline-block;"><i class="fa fa-industry icon-white" style="margin:10px 0 0 2px"></i> </div>中高污與違規農地工廠</div>';
html += '<div><div class="" tabindex="0" style="position:static;width: 35px;height: 35px;display:inline-block;vertical-align: middle;"><svg width="30" height="30"><g><circle cx="15" cy="15" r="10" stroke-width="3" stroke="#FFF" stroke-opacity="0.8" fill="#00E800"></circle></g></svg></div>空氣品質指標</div>';
html += '<div><div class="" tabindex="0" style="position:static;width: 35px;height: 35px;display:inline-block;vertical-align: middle;"><svg width="30" height="30"><g><polygon fill="#9CFF9C" fill-opacity="1.0" stroke="#FFF" stroke-opacity="0.7" stroke-width="1" stroke-miterlimit="10" points="15,0 3,15 15,30 27,15"/></g></svg></div>微型監測站</div>';
this._div.innerHTML = html;
return this._div;
}
maplayers.legend.addTo(map);
}
var layerAirquality = function(map){
maplayers.airquality = L.geoJson();
if(mapopt.airquality.enabled && !map.hasLayer(maplayers.airquality)){
$.getJSON(o.airquality, function(airjson){
maplayers.airquality = L.geoJson(airjson, {
pointToLayer: function (feature, latlng) {
var prop = feature.properties;
var color = colorPlate('AQI', prop['AQI']);
return circleMarker = L.circleMarker(latlng, {
radius: 8,
fillColor: color,
color: "#FFF",
weight: 3,
opacity: 0.8,
fillOpacity: 0.8,
className: 'airq-station'
});
},
onEachFeature: function (feature, layer) {
var popupText = '';
popupText += ' <div class="station">' + feature.properties['sitename'] + '測站</div>';
var pm25 = feature.properties['pm2.5'];
var color = colorPlate('pm25', pm25);
var level = '';
// AQI
var AQI = feature.properties['aqi'];
level = '';
color = colorPlate('AQI', AQI);
if(AQI > 300) { level = '危害'; }
else if(AQI > 200) { level = '非常不健康'; }
else if(AQI > 150) { level = '對所有族群不健康'; }
else if(AQI > 100) { level = '對敏感族群不健康'; }
else if(AQI > 50) { level = '普通'; }
else { level = '良好'; }
popupText += '<label>AQI</label>' + '<div class="aqivalue" style="color: #555; border-color:'+color+'; font-size: 16px;">' + AQI + ','+level+'</div>';
// pm 2.5
if(pm25 >= 70) { level = '非常高'; }
else if(pm25 >= 54) { level = '高'; }
else if(pm25 >= 36) { level = '中'; }
else { level = '低'; }
popupText += '<label>PM2.5</label>' + '<div class="pmvalue" style="color: #555;border-color:'+color+'">' + feature.properties['pm2.5'] + ','+level+'</div>';
popupText += '<div class="time">資料更新時間:' + feature.properties['PublishTime'] + '</div>';
layer.bindPopup(popupText);
}
});
maplayers.airquality.setZIndex(1000);
if(typeof map != 'undefined'){
maplayers.airquality.addTo(map);
// fixes hover problem
// https://github.com/Leaflet/Leaflet.markercluster/issues/431
var svg = $('#'+mapid+' .leaflet-overlay-pane svg');
setTimeout(function(){
$('#'+mapid+' .leaflet-overlay-pane svg > g').each(function(){
if($(this).children('.airq-station').length > 0){
$(this).appendTo(svg);
}
});
}, 2000);
}
});
}
else
if(!mapopt.airquality.enabled && map.hasLayer(maplayers.airquality)){
map.removeLayer(maplayers.airquality);
}
}
var layerAirbox = function(map){
maplayers.airbox = L.geoJson();
if(mapopt.airbox.enabled && !map.hasLayer(maplayers.airbox)){
var selectedBox;
$.getJSON(o.airbox, function(airboxjson){
maplayers.airbox = L.geoJson(airboxjson, {
pointToLayer: function (box, latlng) {
var prop = box.properties;
var pm25 = 0;
if (typeof prop['pm25'] !== 'undefined') {
pm25 = parseInt(prop['pm25']);
}
var color = colorPlate('pm25', pm25);
var diamonMarker = L.shapeMarker(latlng, {
fillColor: color,
color: "#FFF",
shape: "diamond",
radius: 8,
stroke: true,
weight: 1,
opacity: 0.7,
fillOpacity: 0.7,
className: 'airbox-box'
});
return diamonMarker;
},
onEachFeature: function(box, layer) {
if(o.airboxPopupCallback && o.airboxPopupCallback.length){
layer.bindPopup(o.factoryPopupLoading, {minWidth:"300"});
(function(b){
layer.on('click', function(e){
mapopt.airbox.id = b['properties']['id'];
hashUpdate(mapopt);
// ga('send', 'event', 'map', 'click-marker', b['properties']['id']);
o.airboxPopupCallback(e, b);
});
layer.getPopup().on('remove', function() {
mapopt.airbox.id = "";
hashUpdate(mapopt);
});
})(box);
}
else{
layer.bindPopup(b['title']);
}
if (mapopt.airbox.id === box['properties']['id']) {
selectedBox = layer;
}
}
});
maplayers.airbox.setZIndex(999);
if(typeof map != 'undefined'){
maplayers.airbox.addTo(map);
if (selectedBox) {
mapobj.panTo(selectedBox.feature.geometry.coordinates);
setTimeout(function(){
selectedBox.fire('click');
}, 500);
}
}
});
}
else
if(!mapopt.airbox.enabled && map.hasLayer(maplayers.airbox)){
map.removeLayer(maplayers.airbox);
}
}
var mapBaseLayer = function(){
var currentZoom = mapobj.getZoom();
if(currentZoom > 12 && mapobj.hasLayer(maplayers.satellite)){
mapobj.removeLayer(maplayers.satellite);
// mapobj.removeLayer(maplayers.twcounty);
mapobj.addLayer(maplayers.osm);
}
else
if(currentZoom <= 12 && mapobj.hasLayer(maplayers.satellite) === false){
mapobj.addLayer(maplayers.satellite);
// mapobj.addLayer(maplayers.twcounty);
mapobj.removeLayer(maplayers.osm);
}
}
/**
* Make a object for osm
*/
var mapInitLayers = function(){
var maxZoom = 17;
var map = L.map(mapid, {
center: mapopt.latlng,
zoom: mapopt.zoom,
scrollWheelZoom: false,
maxZoom: 17
});
window.mapobj = map;
if(!mapobj.hasLayer(maplayers.osm)) {
layerOsm(map);
}
if(!mapobj.hasLayer(maplayers.satellite)) {
layerSatellite(map);
}
if(!mapobj.hasLayer(maplayers.twcounty)) {
if(!/MSIE/.test(navigator.userAgent) && !/Edge/.test(navigator.userAgent) && !/Trident/.test(navigator.userAgent)){
layerTWCounty(map);
}
}
if(!mapobj.hasLayer(maplayers.factory)) {
layerFactory(map);
layerFactoryLabel(map);
}
if(!mapobj.hasLayer(maplayers.airquality)) {
layerAirquality(map);
}
if(!mapobj.hasLayer(maplayers.airbox)) {
layerAirbox(map);
}
if(!mapobj.hasLayer(maplayers.search)) {
layerSearch(map);
}
mapBaseLayer();
map.on('dragend', mapMove);
map.on('zoomend', function(){
mapMove();
mapBaseLayer();
});
// binding option
if (o.formBinding && typeof window.formBindMarker == 'undefined') {
window.formBindMarker = true;
$(o.formBinding).bindings('create')(mapopt);
if (mapopt.factory.address.length > 0) {
$(o.formBinding).find(".nice-select").find('.current').html($("#edit-factory-address option[value="+mapopt.factory.address+"]").text());
$(o.formBinding).find(".nice-select .list").find("li[data-value="+mapopt.factory.address+"]").addClass("selected focus");
}
// change
$(o.formBinding).on('model-change', function(e, path, value, model, name, element) {
hashUpdate(model);
var status;
if(path == 'airquality.enabled'){
status = value ? 'on' : 'off';
//ga('send', 'event', 'map', 'search-airquality', status);
formControl(model);
}
if(path == 'airbox.enabled'){
status = value ? 'on' : 'off';
//ga('send', 'event', 'map', 'search-airbox', status);
formControl(model);
}
if(path == 'factory.enabled') {
mapToggleLayer(maplayers.factory, 'remove');
formControl(model);
}
if(path == 'factory.address') {
model.factory.enabled = 1;
layerSearch(map);
mapToggleLayer(maplayers.factory, 'remove');
formControl(model);
}
if(path == 'factory.finehard') {
mapopt.factory.fine = 1;
}
if(
path == 'factory.type' ||
path == 'factory.poltype' ||
path == 'factory.fine' ||
path == 'factory.finehard' ||
path == 'factory.realtime' ||
path == 'factory.illegal' ||
path == 'factory.overhead') {
model.factory.enabled = 1;
//ga('send', 'event', 'map', 'search-'+path.replace('.', '-'), value);
mapToggleLayer(maplayers.factory, 'remove');
formControl(model);
}
});
// submit button
// trigger search function
$(o.formBinding).find("input[type=submit]").click(function(e){
e.preventDefault();
mapToggleLayer(maplayers.factory, 'remove');
formLoading(true);
layerFactory(mapobj);
return false;
});
$(o.formBinding).submit(function(e){
e.preventDefault();
return false;
});
}
return map;
}
/**
* Help function for leaflet drag event
*/
var mapMove = function(){
var center = mapobj.getCenter();
var zoom = mapobj.getZoom();
var opt = {
"latlng": [center.lat, center.lng],
"zoom": zoom,
};
hashUpdate(opt);
}
var mapToggleLayer = function(layer, action){
if(action === 'add') {
mapobj.addLayer(layer);
}
else if(mapobj.hasLayer(layer)) {
if(action === 'remove') {
mapobj.removeLayer(layer);
}
}
}
/**
* Help function for update hashtag
*/
var hashUpdate = function(opt){
if(opt){
var newopt = {};
$.extend(newopt, mapopt, opt);
window.location.hash = JSON.stringify(newopt);
mapopt = newopt;
}
if ($("input#copy").length) {
var loc = window.location.origin;
loc = loc + '/envmap?qt-front_content=0' + window.location.hash;
$("input#copy").val(loc);
}
}
/**
* Help function for get hashtag value
*/
var hashResolv = function(method){
var f = window.location.hash.replace(/^#/, '');
if(f){
f = decodeURIComponent(f);
var testjson = /^[\],:{}\s]*$/.test(f.replace(/\\["\\\/bfnrtu]/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''));
if(testjson){
var opt = JSON.parse(f);
if(opt.hasOwnProperty('latlng')){
// override global opt
mapopt = opt;
if (o.formBinding) {
$(o.formBinding).bindings('update')(mapopt);
}
}
}
}
if(method){
return mapopt[method];
}
return mapopt;
}
var replaceToken = function(string, token){
for(var t in token) {
string = string.replace(t, token[t]);
}
return string;
}
var mapReset = function(){
hashResolv();
hashUpdate(mapopt);
$('#'+mapid).remove();
$('<div id="'+mapid+'" class="map"><div id="progress"><div id="progress-bar"></div></div></div>').prependTo(current);
// initialize map height
$(".map").height($(window).height() - 80);
mapInitLayers();
}
var emptyResult = function(display) {
var $empty = $(o.formBinding).find('.empty');
if (!$empty.length) {
var $empty = $('<div class="empty">');
$empty.append('<p><i class="fa fa-info-circle"></i> 您目前的搜尋條件沒有找到結果,請試著清空搜尋條件看看!</p>');
$empty.prependTo(o.formBinding);
}
if (display) {
$empty.show();
}
else {
$empty.hide();
}
}
var formLoading = function(display) {
var $loading = $(o.formBinding).find('.freeze');
if (!$loading.length) {
var $loading = $('<div class="freeze">');
$loading.append('<i class="fa fa-spinner fa-spin"></i>');
$loading.prependTo(o.formBinding);
$loading.height($(o.formBinding).height());
$loading.width('100%');
}
if (display) {
$loading.show();
}
else {
$loading.hide();
}
}
var formControl = function(model){
var show;
// factory layer show hide
if(model.factory.enabled) {
show = true;
}
else{
show = false;
}
for (var ele in model.factory) {
var dataModel = 'factory\\.'+ele;
var $fieldset = $('[data-model='+dataModel+']').closest('fieldset');
if($fieldset.length) {
if(show){
$fieldset.show();
if(!mapobj.hasLayer(maplayers.factory)) {
mapToggleLayer(maplayers.factory, 'remove');
formLoading(true);
layerFactory(mapobj);
}
}
else{
mapToggleLayer(maplayers.factory, 'remove');
$fieldset.hide();
}
break;
}
}
// overhead form element
dataModel = 'factory\\.overhead';
$fieldset = $('[data-model='+dataModel+']').closest('fieldset');
if($fieldset.length){
if(model.factory.realtime) {
$fieldset.show();
}
else{
$('[data-model='+dataModel+']').prop('checked', false);
$('[data-model=factory\\.overhead]').prop('checked', false);
$fieldset.hide();
}
}
// air quality layer control
if (model.airquality.enabled) {
if(!mapobj.hasLayer(maplayers.airquality)) {
layerAirquality(mapobj);
}
}
else {
mapToggleLayer(maplayers.airquality, 'remove');
}
// air box layer control
if (model.airbox.enabled) {
if(!mapobj.hasLayer(maplayers.airbox)) {
layerAirbox(mapobj);
}
mapToggleLayer(maplayers.airbox, 'add');
}
else {
mapToggleLayer(maplayers.airbox, 'remove');
}
}
/**
* Main function for start map. callback after json loaded
*/
var mapStart = function(pos){
started = true;
if(typeof pos != 'undefined' && typeof pos.coords != 'undefined'){
mapopt.latlng = [pos.coords.latitude, pos.coords.longitude];
window.userPos = [pos.coords.latitude, pos.coords.longitude];
}
var resizing = 0;
$(window).resize(function(){
if(!resizing){
resizing = 1;
window.setTimeout(function(){
resizing = 0;
mapReset();
}, 600);
}
});
mapReset();
}
// main
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
navigator.geolocation.getCurrentPosition(mapStart, mapStart, options);
window.setTimeout(function(){
if (!started) {
mapStart();
}
}, 3000);
}
}(jQuery));