-
Notifications
You must be signed in to change notification settings - Fork 0
/
leafletMulti.html
2039 lines (1730 loc) · 80.4 KB
/
leafletMulti.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tree Planting Map</title>
<link rel="stylesheet" href="https://unpkg.com/leaflet/dist/leaflet.css" />
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.1/css/all.css">
<style>
body {
display: flex;
font-family: 'Arial', sans-serif;
margin:0px;
}
#sidebar {
width: 300px;
padding: 20px;
display: flex;
flex-direction: column;
gap: 15px;
background-color: #f4f4f4;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
#map {
height: 100vh;
flex-grow: 1;
}
.input-group {
margin: 15px 0;
display: flex;
flex-direction: column;
}
.input-group label {
margin-bottom: 5px;
font-weight: bold;
}
.input-group input {
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
}
button {
margin-top:10px;
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s ease;
}
button:hover {
background-color: #45a049;
}
/* Style for the custom checkbox */
.custom-checkbox {
display: inline-block;
position: relative;
padding-left: 25px;
cursor: pointer;
font-size: 16px;
line-height: 20px;
user-select: none;
}
/* Hide the default checkbox */
.custom-checkbox input {
position: absolute;
opacity: 0;
cursor: pointer;
height: 0;
width: 0;
}
/* Create a custom checkbox */
.checkmark {
position: absolute;
top: 0;
left: 0;
height: 20px;
width: 20px;
background-color: #eee;
border-radius: 4px;
}
/* When the checkbox is checked, add a blue background */
.custom-checkbox input:checked ~ .checkmark {
background-color: #2196F3;
}
/* Create the checkmark/indicator (hidden when not checked) */
.checkmark:after {
content: "\f00c"; /* Correct code for FontAwesome checkmark */
font-family: "Font Awesome 5 Free";
font-weight: 900; /* FontAwesome 5 requires explicit font-weight for solid icons */
position: absolute;
display: none;
color: white;
top: -2px;
left: 5px;
font-size: 14px;
}
/* Show the checkmark when checked */
.custom-checkbox input:checked ~ .checkmark:after {
display: block;
}
/* Style the checkmark/indicator */
.custom-checkbox .checkmark:after {
left: 5px;
top: 0px;
}
.district-label-tooltip {
background-color: transparent;
border: none;
box-shadow: none;
font-size: 14px;
color: black;
text-align: center;
padding: 0;
pointer-events: none;
z-index: 1000000;
}
.district-label {
font-weight: normal;
z-index: 1000000;
}
</style>
</head>
<body>
<div id="sidebar">
<h2><i class="fas fa-tree"></i> Tree Planting Parameters</h2>
<form id="parametersForm">
<div class="input-group">
<label for="boroSelect">Select Borough:</label>
<select id="boroSelect" data-current="">
<!-- Options will be dynamically added -->
</select>
</div>
<div class="input-group">
<label for="totalTrees">Total Trees:</label>
<input type="number" id="totalTrees" name="totalTrees" value="100">
</div>
<div class="input-group">
<label for="coolingEffect">Cooling Effect:</label>
<input type="number" id="coolingEffect" name="coolingEffect" step="1" value="1">
</div>
<div class="input-group">
<label for="coolingDistance">Cooling Distance (meters):</label>
<input type="number" id="coolingDistance" name="coolingDistance" value="500">
</div>
<button type="button" onclick="updateTreePlanting()">Update Tree Planting</button>
<button type="button" onclick="clearPlantedTrees()">Clear Planted Trees</button>
<h4 id="results">...</h4>
<div class="input-group">
<label>Effect Type:</label>
<label><input type="radio" name="effectType" value="binary" onchange="toggleGaussianSettings()" checked> Binary</label>
<label><input type="radio" name="effectType" value="gaussian" onchange="toggleGaussianSettings()"> Gaussian</label>
</div>
<div id="gaussianSettings" style="display: none;">
<div class="input-group">
<label for="gaussianSigma">Gaussian Sigma:</label>
<input type="number" id="gaussianSigma" name="gaussianSigma" step="0.1" value="1">
</div>
<div class="input-group">
<label for="gaussianAmplitude">Gaussian Amplitude:</label>
<input type="number" id="gaussianAmplitude" name="gaussianAmplitude" step="0.1" value="1">
</div>
</div>
<label class="custom-checkbox">Show Heat Index
<input type="checkbox" id="heatIndexToggle" name="heatIndexToggle" onchange="toggleHeatIndex()">
<span class="checkmark"></span>
</label>
<div id="heatIndexSettings" style="display: none;">
<div class="input-group" style="display: none;">
<label for="heatIndexScale">Heat Index Scale:</label>
<input type="range" id="heatIndexScale" name="heatIndexScale" min="0.1" max="10" step="0.1" value="1">
</div>
</div>
<!-- Tree Data Toggle and Settings -->
<label class="custom-checkbox">View Tree Data
<input type="checkbox" id="treeToggleView" name="treeToggleView" onchange="toggleTreeSettings()">
<span class="checkmark"></span>
</label>
<div id="treeSettings" style="display: none;">
<label class="custom-checkbox">Show Tree Radius
<input type="checkbox" id="treeRadiusToggle" name="treeRadiusToggle" onchange="toggleTreeRadius()" checked>
<span class="checkmark"></span>
</label>
<div class="input-group">
<label for="treeCoolingEffect">Tree Cooling Effect:</label>
<input type="number" id="treeCoolingEffect" name="treeCoolingEffect" step="0.1" value="0.1">
</div>
<div class="input-group">
<label for="treeCoolingDistance">Tree Cooling Distance (meters):</label>
<input type="number" id="treeCoolingDistance" name="treeCoolingDistance" value="20">
</div>
</div>
<!-- School Data Toggle and Settings -->
<label class="custom-checkbox">View School Data
<input type="checkbox" id="schoolToggleView" name="schoolToggleView" onchange="toggleSchoolSettings()">
<span class="checkmark"></span>
</label>
<div id="schoolSettings" style="display: none;">
<label class="custom-checkbox">Show School Radius
<input type="checkbox" id="schoolRadiusToggle" name="schoolRadiusToggle" onchange="toggleSchoolRadius()" checked>
<span class="checkmark"></span>
</label>
<div class="input-group">
<label for="schoolHeatingEffect">School Heating Effect:</label>
<input type="number" id="schoolHeatingEffect" name="schoolHeatingEffect" step="0.1" value="0.1">
</div>
<div class="input-group">
<label for="schoolHeatingDistance">School Heating Distance (meters):</label>
<input type="number" id="schoolHeatingDistance" name="schoolHeatingDistance" value="500">
</div>
</div>
<!-- Facility Data Toggle and Settings -->
<label class="custom-checkbox">View Facility Data
<input type="checkbox" id="facilityToggleView" name="facilityToggleView" onchange="toggleFacilitySettings()">
<span class="checkmark"></span>
</label>
<div id="facilitySettings" style="display: none;">
<label class="custom-checkbox">Show Facility Radius
<input type="checkbox" id="facilityRadiusToggle" name="facilityRadiusToggle" onchange="toggleFacilityRadius()" checked>
<span class="checkmark"></span>
</label>
<div class="input-group">
<label for="facilityHeatingEffect">Facility Heating Effect:</label>
<input type="number" id="facilityHeatingEffect" name="facilityHeatingEffect" step="0.1" value="0.1">
</div>
<div class="input-group">
<label for="facilityHeatingDistance">Facility Heating Distance (meters):</label>
<input type="number" id="facilityHeatingDistance" name="facilityHeatingDistance" value="500">
</div>
</div>
<!-- Add the following in the sidebar section of the HTML -->
<label class="custom-checkbox">View Street Data
<input type="checkbox" id="streetToggleView" name="streetToggleView" onchange="toggleStreetSettings()">
<span class="checkmark"></span>
</label>
<div id="streetSettings" style="display: none;">
<label class="custom-checkbox">Show Street Buffer
<input type="checkbox" id="streetBufferToggle" name="streetBufferToggle" onchange="toggleStreetBuffer()" checked>
<span class="checkmark"></span>
</label>
<div class="input-group">
<label for="streetEffect">Street Effect:</label>
<input type="number" id="streetEffect" name="streetEffect" step="0.1" value="0.1">
</div>
<div class="input-group">
<label for="streetBufferDistance">Street Buffer Distance (meters):</label>
<input type="number" id="streetBufferDistance" name="streetBufferDistance" value="5">
</div>
<div class="input-group">
<label for="streetWeightField">Street Weight Field:</label>
<select id="streetWeightField" name="streetWeightField">
<option value="SHAPE_Length">SHAPE_Length</option>
<option value="StreetWidth_Min">StreetWidth_Min</option>
<option value="StreetWidth_Max">StreetWidth_Max</option>
<option value="BikeLane">BikeLane</option>
<option value="Number_Travel_Lanes">Number_Travel_Lanes</option>
<option value="Number_Park_Lanes">Number_Park_Lanes</option>
<option value="Number_Total_Lanes">Number_Total_Lanes</option>
<option value="POSTED_SPEED">POSTED_SPEED</option>
</select>
</div>
</div>
<label class="custom-checkbox">Planting View
<input type="checkbox" id="plantingViewToggle" name="plantingViewToggle">
<span class="checkmark"></span>
</label>
</form>
</div>
<div id="map"></div>
<script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/src/leaflet.geometryutil.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@turf/turf@6/turf.min.js"></script>
<script src="https://unpkg.com/[email protected]/leaflet-shapefile.js"></script>
<script src="shp.js"></script>
<script src="leaflet.shpfile.js"></script>
<script>
var map = L.map('map',
{
renderer: L.canvas() // Set Canvas as the default renderer for all layers
}).setView([40.642935, -73.930188], 13);
// L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
// attribution: '© OpenStreetMap contributors'
// }).addTo(map);
L.tileLayer('https://{s}.basemaps.cartocdn.com/rastertiles/light_all/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors, © CartoDB'
}).addTo(map);
var plantableAreasPane = map.createPane('plantableAreasPane');
plantableAreasPane.style.zIndex = 1000000;
// Global variable to keep track of the current GeoJSON layer
var currentGeoJsonLayer = null;
// function displayGeoJson(geojsonData) {
// if (currentGeoJsonLayer) {
// map.removeLayer(currentGeoJsonLayer);
// }
// currentGeoJsonLayer = L.geoJson(geojsonData, {
// style: function(feature) {
// // try by color
// return { color: feature.properties.color, weight: 2, fillOpacity: 0.5 };
// // return { color: getColor(feature.properties._mean, heatIndexScale), weight: 2, fillOpacity: 0.5 };
// },
// pane: 'plantableAreasPane', // Set the custom pane for the plantable areas layer
// renderer: L.canvas() // Set Canvas as the renderer for this layer
// }).addTo(map);
// }
function displayGeoJson(geojsonData) {
if (currentGeoJsonLayer) {
map.removeLayer(currentGeoJsonLayer);
}
currentGeoJsonLayer = L.geoJson(geojsonData, {
style: function(feature) {
return {
color: feature.properties.color,
weight: 2,
fillOpacity: 0.5
};
},
pane: 'plantableAreasPane',
renderer: L.canvas()
}).addTo(map);
}
function displayHeatIndexGeoJson(geojsonData, heatIndexScale) {
if (currentGeoJsonLayer) {
map.removeLayer(currentGeoJsonLayer);
}
currentGeoJsonLayer = L.geoJson(geojsonData, {
style: function(feature) {
return { color: getColor(feature.properties._mean, heatIndexScale), weight: 2, fillOpacity: 0.5 };
}
}).addTo(map);
}
function updateTreePlanting() {
var totalTrees = parseInt(document.getElementById('totalTrees').value);
var coolingEffect = parseFloat(document.getElementById('coolingEffect').value);
var coolingDistance = parseInt(document.getElementById('coolingDistance').value);
// Clear existing tree markers
clearMapLayers();
// Example values for schoolEffect and schoolDistance, replace with actual input retrieval
let schoolEffect = parseFloat(document.getElementById('schoolHeatingEffect').value);
let schoolDistance = parseInt(document.getElementById('schoolHeatingDistance').value);
// Example values for treeEffect and treeDistance, replace with actual input retrieval
let treeEffect = parseFloat(document.getElementById('treeCoolingEffect').value);
let treeDistance = parseInt(document.getElementById('treeCoolingDistance').value);
// Example values for facilityEffect and facilityDistance, replace with actual input retrieval
let facilityEffect = parseFloat(document.getElementById('facilityHeatingEffect').value);
let facilityDistance = parseInt(document.getElementById('facilityHeatingDistance').value);
let streetEffect = parseFloat(document.getElementById('streetEffect').value);
let streetBufferDistance = parseInt(document.getElementById('streetBufferDistance').value);
let streetWeightField = document.getElementById('streetWeightField').value;
// Pass the additional parameters for streets to the planting function
PlantTrees(originalGeoJsonData, totalTrees, coolingEffect, coolingDistance, schoolEffect, schoolDistance, treeEffect, treeDistance, facilityEffect, facilityDistance, streetEffect, streetBufferDistance, streetWeightField);
}
function clearMapLayers() {
// Modified to remove only tree markers, preserving the GeoJSON layer
map.eachLayer(function(layer) {
if (layer instanceof L.Marker) {
map.removeLayer(layer);
}
});
}
function calculateCentroid(geometry) {
let centroid = [0, 0];
let totalPoints = 0;
if (geometry.type === "Polygon") {
geometry.coordinates[0].forEach(coord => {
centroid[0] += coord[0]; // longitude
centroid[1] += coord[1]; // latitude
totalPoints++;
});
} else if (geometry.type === "MultiPolygon") {
geometry.coordinates.forEach(polygon => {
let polygonCentroid = [0, 0];
let polygonPoints = 0;
polygon[0].forEach(coord => { // Only using the first ring
polygonCentroid[0] += coord[0];
polygonCentroid[1] += coord[1];
polygonPoints++;
});
centroid[0] += polygonCentroid[0] / polygonPoints; // Average for this polygon
centroid[1] += polygonCentroid[1] / polygonPoints;
totalPoints += 1; // We're averaging centroids, so each polygon counts as one "point"
});
}
centroid[0] /= totalPoints; // Final average
centroid[1] /= totalPoints;
return [centroid[1], centroid[0]]; // Leaflet uses [lat, lng] format
}
function PlantTrees(originalGeoJsonData, totalTrees, coolingEffect, coolingDistance, schoolEffect, schoolDistance, treeEffect, treeDistance, facilityEffect, facilityDistance, streetEffect, streetBufferDistance, streetWeightField) {
let geojsonData = JSON.parse(JSON.stringify(originalGeoJsonData));
// Apply effects from schools and existing trees
geojsonData = applySchoolEffect(geojsonData, schoolEffect, schoolDistance);
geojsonData = applyTreeEffect(geojsonData, treeEffect, treeDistance);
geojsonData = applyFacilityEffect(geojsonData, facilityEffect, facilityDistance);
geojsonData = applyStreetEffect(geojsonData, streetEffect, streetBufferDistance, streetWeightField);
let plantableAreas = geojsonData.features.filter(feature => feature.properties.canopy_type === 'plantable');
let treesPlanted = 0;
while (treesPlanted < totalTrees && plantableAreas.length > 0) {
// Calculate the combined mean for each plantable area
plantableAreas.forEach(area => {
// if heat index is on, add the heat index to the mean
if (showHeatIndex) {
area.properties._combinedMean = (area.properties._mean || 0) + (area.properties._schoolmean || 0) + (area.properties._treemean || 0) + (area.properties._facilitymean || 0);
} else {
area.properties._combinedMean = (area.properties._schoolmean || 0) + (area.properties._treemean || 0) + (area.properties._facilitymean || 0);
}
});
// Sort plantable areas by _combinedMean property in descending order
plantableAreas.sort((a, b) => b.properties._combinedMean - a.properties._combinedMean);
const plantingArea = plantableAreas[0];
const centroid = calculateCentroid(plantingArea.geometry);
placeTreeOnMap(centroid);
treesPlanted++;
// Apply cooling effect to the planted area if applicable
// Apply cooling effect to the planted area if applicable
if (coolingEffect > 0) {
plantingArea.properties._treemean = (plantingArea.properties._treemean || 0) - coolingEffect;
if (document.getElementById('plantingViewToggle').checked) {
plantingArea.properties._displayMean = (plantingArea.properties._mean || 0) + (plantingArea.properties._schoolmean || 0) + plantingArea.properties._treemean;
}
}
// Filter and adjust remaining plantable areas considering cooling effect and distance
plantableAreas = plantableAreas.slice(1).filter(area => {
const areaCentroid = calculateCentroid(area.geometry);
const distance = getDistance(centroid[0], centroid[1], areaCentroid[0], areaCentroid[1]);
if (coolingDistance > 0 && distance <= coolingDistance && coolingEffect > 0) {
area.properties._treemean = (area.properties._treemean || 0) - coolingEffect * (coolingDistance - distance) / coolingDistance;
}
return area.properties._combinedMean > 0;
});
}
if (treesPlanted < totalTrees) {
console.log(`Planted ${treesPlanted} trees. Ran out of suitable planting areas.`);
document.getElementById('results').innerText = `Planted ${treesPlanted} trees. Ran out of suitable planting areas.`;
} else {
console.log(`Successfully planted all ${totalTrees} trees.`);
document.getElementById('results').innerText = `Successfully planted all ${totalTrees} trees.`;
}
if (document.getElementById('plantingViewToggle').checked) {
calculateMinMaxMean(geojsonData);
updateMeanColors(geojsonData);
displayGeoJson(geojsonData);
}
}
function placeTreeOnMap(centroid) {
L.marker(centroid).addTo(map);
}
function getDistance(lat1, lon1, lat2, lon2) {
// Haversine formula to calculate distance between two points on Earth
var R = 6371e3; // Earth's radius in meters
var φ1 = lat1 * Math.PI / 180;
var φ2 = lat2 * Math.PI / 180;
var Δφ = (lat2 - lat1) * Math.PI / 180;
var Δλ = (lon2 - lon1) * Math.PI / 180;
var a = Math.sin(Δφ / 2) * Math.sin(Δφ / 2) +
Math.cos(φ1) * Math.cos(φ2) *
Math.sin(Δλ / 2) * Math.sin(Δλ / 2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return R * c; // in meters
}
// function getDistance(lat1, lon1, lat2, lon2) {
// // Euclidean distance between two points on Earth
// var x = (lon2 - lon1) * Math.cos((lat1 + lat2) / 2);
// var y = (lat2 - lat1);
// return Math.sqrt(x * x + y * y); // in meters
// }
function getColor(heatIndex, scale) {
console.log("max and min mean", maxMean, minMean);
const range = maxMean - minMean;
const normalizedIndex = (heatIndex - minMean) / range;
const scaledIndex = Math.pow(normalizedIndex, scale);
// Interpolate between green (0), orange (0.5), and red (1)
if (scaledIndex < 0.5) {
// Mix between green and orange
const mix = scaledIndex * 2;
return mixColor('#008000', '#ff8c00', mix);
} else {
// Mix between orange and red
const mix = (scaledIndex - 0.5) * 2;
return mixColor('#ff8c00', '#ff0000', mix);
}
}
var showHeatIndex = false;
var heatIndexScale = 1;
function toggleHeatIndex() {
showHeatIndex = document.getElementById('heatIndexToggle').checked;
console.log("Show heat index:", showHeatIndex);
document.getElementById('heatIndexSettings').style.display = showHeatIndex ? 'block' : 'none';
// updateHeatIndexScale();
updatePlantableAreaColors();
}
function updateHeatIndexScale() {
heatIndexScale = parseFloat(document.getElementById('heatIndexScale').value);
if (showHeatIndex) {
// calculateMinMaxMean(originalGeoJsonData)
// displayHeatIndexGeoJson(originalGeoJsonData, heatIndexScale);
displayGeoJson(originalGeoJsonData);
} else {
// calculateMinMaxMean(originalGeoJsonData)
displayGeoJson(originalGeoJsonData);
}
}
function mixColor(color1, color2, weight) {
var color1Rgb = hexToRgb(color1),
color2Rgb = hexToRgb(color2),
r = Math.round(mix(color1Rgb.r, color2Rgb.r, weight)),
g = Math.round(mix(color1Rgb.g, color2Rgb.g, weight)),
b = Math.round(mix(color1Rgb.b, color2Rgb.b, weight));
return rgbToHex(r, g, b);
}
function mix(start, end, weight) {
return start + (end - start) * weight;
}
function hexToRgb(hex) {
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
}
function rgbToHex(r, g, b) {
return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
}
var originalGeoJsonData;
var minMean, maxMean;
// function calculateMinMaxMean(geojsonData) {
// // check what features are enabled and calculate min and max mean
// treemean = [];
// schoolmean = [];
// heatmean = [];
// if(document.getElementById('treeToggleView').checked) {
// treemean = geojsonData.features.map(feature => feature.properties._treemean);
// }
// if(document.getElementById('schoolToggleView').checked) {
// schoolmean = geojsonData.features.map(feature => feature.properties._schoolmean);
// }
// if(document.getElementById('heatIndexToggle').checked) {
// heatmean = geojsonData.features.map(feature => feature.properties._mean);
// }
// means = treemean.concat(schoolmean, heatmean);
// console.log(means);
// // cast out the undefined values
// means = means.filter(function (el) {
// return el != null;
// });
// // const means = geojsonData.features.map(feature => feature.properties.);
// minMean = Math.min(...means);
// maxMean = Math.max(...means);
// if (minMean === maxMean) {
// minMean = 0;
// maxMean = 1;
// }
// // if infinity
// if (minMean === Infinity) {
// minMean = 0;
// maxMean = 1;
// }
// console.log("Calculated min and max mean values:", minMean, maxMean);
// }
function calculateMinMaxMean(geojsonData) {
var means = geojsonData.features.map(feature => {
if (feature.properties.canopy_type === 'plantable') {
return feature.properties._displayMean;
}
}).filter(mean => mean !== undefined);
minMean = Math.min(...means);
maxMean = Math.max(...means);
if (minMean === maxMean) {
minMean = 0;
maxMean = 1;
}
if (minMean === Infinity) {
minMean = 0;
maxMean = 1;
}
console.log("Calculated min and max mean values:", minMean, maxMean);
}
// $.getJSON('inputStreet.geojson', function(data) {
// originalGeoJsonData = data;
// calculateMinMaxMean(originalGeoJsonData); // Calculate min and max mean values
// // displayGeoJson(originalGeoJsonData, showHeatIndex, heatIndexScale);
// // set color to default '#008000' on load
// // originalGeoJsonData.features.forEach(feature => {
// // feature.properties.color = '#008000';
// // });
// displayGeoJson(originalGeoJsonData);
// $.getJSON('schoolsBK17.geojson', function(data) {
// L.geoJson(data).eachLayer(function(layer) {
// schoolLayer.addLayer(layer); // This should add each school to the schoolLayer
// });
// console.log(schoolLayer.getLayers().length); // This should now log a non-zero number
// // drawLinesToSchoolsWithinRadius();
// });
// });
function drawLinesToClosestSchoolFromLayer() {
originalGeoJsonData.features.forEach(plantableArea => {
if (plantableArea.properties.canopy_type === 'plantable') {
const plantableCentroid = calculateCentroid(plantableArea.geometry);
let closestSchoolPoint = null;
let minDistance = Infinity;
console.log(schoolLayer);
// log the length of the schoolLayer to ensure it's not empty
console.log(schoolLayer.getLayers().length);
schoolLayer.eachLayer(function(layer) {
let schoolPoint;
if (layer.feature && layer.feature.geometry) {
// Handle MultiPoint geometry
if (layer.feature.geometry.type === 'MultiPoint') {
// Assuming we're interested in the first point of the MultiPoint
const firstPointCoords = layer.feature.geometry.coordinates[0];
schoolPoint = [firstPointCoords[1], firstPointCoords[0]]; // Correct [lat, lng] order for Leaflet
} else {
// For simplicity, handling other types as before (assuming Point)
schoolPoint = [layer.feature.geometry.coordinates[1], layer.feature.geometry.coordinates[0]];
}
} else if (layer.getLatLng) {
// This is for layers that are not GeoJSON (e.g., L.Marker, L.CircleMarker)
let latLng = layer.getLatLng();
schoolPoint = [latLng.lat, latLng.lng]; // Leaflet uses [lat, lng]
} else {
console.log('Unknown layer type or geometry not defined');
return; // Skip this layer if it doesn't have recognizable geometry
}
// Calculate distance (ensure your getDistance function is using the correct coordinate order)
const distance = getDistance(plantableCentroid[0], plantableCentroid[1], schoolPoint[0], schoolPoint[1]);
console.log(plantableCentroid);
console.log(schoolPoint);
console.log(distance);
if (distance < minDistance) {
closestSchoolPoint = schoolPoint;
minDistance = distance;
}
});
// When adding to map, ensure closestSchoolPoint is correctly structured
if (closestSchoolPoint) {
L.polyline([
// [plantableCentroid[1], plantableCentroid[0]],
[plantableCentroid[0], plantableCentroid[1]],
closestSchoolPoint // This should be [lat, lng]
], {
color: 'blue',
weight: 1,
opacity: 0.5
}).addTo(map);
}
}
});
}
function drawLinesToSchoolsWithinRadius() {
const radius = 1000; // Define your radius in meters
originalGeoJsonData.features.forEach(plantableArea => {
if (plantableArea.properties.canopy_type === 'plantable') {
const plantableCentroid = calculateCentroid(plantableArea.geometry);
// No longer keeping track of the closest school or minimum distance
console.log(schoolLayer);
console.log(schoolLayer.getLayers().length);
schoolLayer.eachLayer(function(layer) {
let schoolPoint;
if (layer.feature && layer.feature.geometry) {
// Handle MultiPoint geometry
if (layer.feature.geometry.type === 'MultiPoint') {
const firstPointCoords = layer.feature.geometry.coordinates[0];
schoolPoint = [firstPointCoords[1], firstPointCoords[0]]; // [lat, lng] order for Leaflet
} else {
// For simplicity, handling other types as before (assuming Point)
schoolPoint = [layer.feature.geometry.coordinates[1], layer.feature.geometry.coordinates[0]];
}
} else if (layer.getLatLng) {
// This is for layers that are not GeoJSON (e.g., L.Marker, L.CircleMarker)
let latLng = layer.getLatLng();
schoolPoint = [latLng.lat, latLng.lng]; // Leaflet uses [lat, lng]
} else {
console.log('Unknown layer type or geometry not defined');
return; // Skip this layer if it doesn't have recognizable geometry
}
// Calculate distance
const distance = getDistance(plantableCentroid[0], plantableCentroid[1], schoolPoint[0], schoolPoint[1]);
console.log(plantableCentroid);
console.log(schoolPoint);
console.log(distance);
// Draw line if within the specified radius
if (distance <= radius) {
L.polyline([
[plantableCentroid[0], plantableCentroid[1]],
schoolPoint // [lat, lng] order
], {
color: 'blue',
weight: 1,
opacity: 0.5
}).addTo(map);
}
});
}
});
}
function loadSchoolDataAndDrawLines() {
$.getJSON('schoolsBK17.geojson', function(data) {
// Assuming this is where you add schools to schoolLayer
L.geoJson(data, {
onEachFeature: function(feature, layer) {
schoolLayer.addLayer(layer);
}
});
// After adding schools to schoolLayer, now draw lines
// drawLinesToClosestSchoolFromLayer();
});
}
// Call this function after your map and datasets have been initialized
// drawLinesToClosestSchoolFromLayer();
var facilityLayer = L.layerGroup(); // Initialize with an empty layer group
var treeLayer = L.layerGroup(); // Initialize with an empty layer group
var schoolLayer = L.layerGroup(); // Initialize with an empty layer group
var treeCircles = [];
var schoolCircles = [];
function toggleTreeData() {
var treeDataVisible = document.getElementById('treeToggleView').checked;
var showTreeRadius = document.getElementById('treeRadiusToggle').checked;
if (treeDataVisible) {
if (!map.hasLayer(treeLayer)) {
$.getJSON('treefolio84.geojson', function(data) {
treeLayer = L.geoJson(data, {
pointToLayer: function(feature, latlng) {
var originalCircle = L.circle(latlng, {radius: 2, fillColor: "#ADD8E6", color: "#ADD8E6", weight: 3, opacity: 1, fillOpacity: 0.8});
var coolingDistance = parseInt(document.getElementById('treeCoolingDistance').value);
var effectCircle = L.circle(latlng, {
color: 'red',
fillOpacity: 0,
radius: coolingDistance
});
treeCircles.push(effectCircle);
if (showTreeRadius) {
effectCircle.addTo(map);
}
originalCircle._coolingCircle = effectCircle;
var group = L.layerGroup([originalCircle]).addTo(map);
return group;
}
}).addTo(map);
});
if (currentGeoJsonLayer) {
currentGeoJsonLayer.bringToFront();
}
}
} else {
if (treeLayer) {
// remove tree circles
treeCircles.forEach(function(circle) {
map.removeLayer(circle);
});
map.removeLayer(treeLayer);
updatePlantableAreaColors();
}
}
}
// function toggleSchoolData() {
// var schoolDataVisible = document.getElementById('schoolToggleView').checked;
// var showSchoolRadius = document.getElementById('schoolRadiusToggle').checked;
// if (schoolDataVisible) {
// if (!map.hasLayer(schoolLayer)) {
// $.getJSON('schoolsBK17.geojson', function(data) {
// schoolLayer = L.geoJson(data, {
// pointToLayer: function(feature, latlng) {
// var originalCircle = L.circleMarker(latlng, {
// radius: 8,
// fillColor: "#ff7800",
// color: "#000",
// weight: 3,
// opacity: 1,
// fillOpacity: 0.8
// });
// var heatingDistance = parseInt(document.getElementById('schoolHeatingDistance').value);
// var effectCircle = L.circle(latlng, {
// color: 'red',
// fillOpacity: 0,
// radius: heatingDistance
// });
// schoolCircles.push(effectCircle);
// if (showSchoolRadius) {
// effectCircle.addTo(map);
// }
// originalCircle._heatingCircle = effectCircle;
// var group = L.layerGroup([originalCircle]).addTo(map);
// return group;
// }
// }).addTo(map);
// });
// }
// } else {
// if (schoolLayer) {
// // remove school circles
// schoolCircles.forEach(function(circle) {
// map.removeLayer(circle);
// });
// map.removeLayer(schoolLayer);
// updatePlantableAreaColors();
// }
// }
// }
function toggleSchoolData() {
var schoolDataVisible = document.getElementById('schoolToggleView').checked;
var showSchoolRadius = document.getElementById('schoolRadiusToggle').checked;
var selectedBorough = document.getElementById('boroSelect').value;
if (schoolDataVisible) {
if (!map.hasLayer(schoolLayer)) {
$.getJSON('borosSchools/boro_cd_' + selectedBorough + '.geojson', function(data) {
schoolLayer.clearLayers();
L.geoJson(data, {
pointToLayer: function(feature, latlng) {
var originalCircle = L.circleMarker(latlng, {
radius: 8,
fillColor: "#ff7800",
color: "#000",
weight: 3,
opacity: 1,
fillOpacity: 0.8
});
var heatingDistance = parseInt(document.getElementById('schoolHeatingDistance').value);
var effectCircle = L.circle(latlng, {
color: 'red',
fillOpacity: 0,
radius: heatingDistance
});
schoolCircles.push(effectCircle);
if (showSchoolRadius) {
effectCircle.addTo(map);
}
originalCircle._heatingCircle = effectCircle;
var group = L.layerGroup([originalCircle]).addTo(map);
return group;
}
}).addTo(schoolLayer);
schoolLayer.addTo(map);
updatePlantableAreaColors();
});
}
} else {
if (schoolLayer) {
// remove school circles
schoolCircles.forEach(function(circle) {
map.removeLayer(circle);
});
map.removeLayer(schoolLayer);
updatePlantableAreaColors();
}
}
}
function updateSchoolHeatingDistance() {
// Update the radius of existing school circles
schoolCircles.forEach(function(circle) {
var heatingDistance = parseInt(document.getElementById('schoolHeatingDistance').value);
circle.setRadius(heatingDistance);
});
updatePlantableAreaColors();
}
function updateTreeCoolingDistance() {
// Update the radius of existing tree circles
treeCircles.forEach(function(circle) {
var coolingDistance = parseInt(document.getElementById('treeCoolingDistance').value);