Repository navigation
Expand file tree
/
Copy pathcesium.js
More file actions
1664 lines (1319 loc) · 61.7 KB
/
Copy pathcesium.js
File metadata and controls
1664 lines (1319 loc) · 61.7 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
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
// document.getElementById('sidebar-toggle').addEventListener('click', function() {
// var sidebar = document.getElementById('sidebar');
// var button = document.getElementById('sidebar-toggle');
// if (sidebar.classList.contains('open')) {
// sidebar.classList.remove('open');
// button.classList.remove('open');
// } else {
// sidebar.classList.add('open');
// button.classList.add('open');
// }
// });
Cesium.Ion.defaultAccessToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI3ODhiN2NhYi02NzgxLTQ2OWQtOTAzMi02ZTgwYmNjMGJmYjYiLCJpZCI6MTM4NjUzLCJpYXQiOjE2ODQxMTUyNDV9.yzVSoiedb3diO7rOG9kd9Luuamx4Wjnieson-zb3vvk";
// Cesium.GoogleMaps.defaultApiKey = "AIzaSyDV0rBF5y2f_xsSNj32fxvhqj3ZErTt6HQ";
// const viewer = new Cesium.Viewer("cesiumContainer", {
// terrainProvider: Cesium.CesiumTerrainProvider.fromIonAssetId(1),
// globe: false,
// });
const viewer = new Cesium.Viewer("cesiumContainer", {
terrainProvider: Cesium.CesiumTerrainProvider.fromIonAssetId(
1
), // start the viewer in located in Austin
});
viewer.scene.globe.depthTestAgainstTerrain = true;
// Initialize scale bar, north arrow, and timestamp
initializeMapControls();
let cesiumTileset; // Store reference to the Cesium tileset
let googleTileset; // Store reference to the Google tileset
async function createGooglePhotorealistic3DTileset() {
try {
const tileset1 = await Cesium.createGooglePhotorealistic3DTileset(
"AIzaSyCxqt6c6a0Az1HZ8Xv3PN1AcSpXhNkPy8k",
{
// maximumScreenSpaceError: 2// The defaults to 16. Lower is higher quality.
}
);
// const tileset1 = new Cesium.Cesium3DTileset({
// url: 'http://localhost:3001/tileset/', // Point this to your caching server
// });
// viewer.scene.primitives.add(tileset);
console.log(tileset1);
googleTileset = tileset1;
window.tileset = tileset1;
viewer.scene.primitives.add(tileset1);
// // viewer.scene.primitives.add(tileset);
// await new Promise((resolve, reject) => {
// // wait 5 seconds
// setTimeout(() => {
// viewer.scene.primitives.add(tileset1);
// console.log("5 seconds passed");
// resolve();
// }, 5000);
// });
// Ready promise 20 seconds
await new Promise((resolve, reject) => {
// wait 5 seconds
setTimeout(() => {
fetchAllData();
console.log("5 seconds passed");
resolve();
}, 500);
});
console.log("Tileset loaded!");
// fetchAllData();
} catch (error) {
console.log(`Failed to load tileset: ${error}`);
}
}
createGooglePhotorealistic3DTileset();
// Load Cesium Tileset
async function createCesiumTileset() {
try {
const tileset = await Cesium.Cesium3DTileset.fromIonAssetId(96188);
cesiumTileset = tileset;
viewer.scene.primitives.add(tileset);
await viewer.zoomTo(tileset);
// Apply the default style if it exists
const extras = tileset.asset.extras;
if (Cesium.defined(extras) && Cesium.defined(extras.ion) && Cesium.defined(extras.ion.defaultStyle)) {
tileset.style = new Cesium.Cesium3DTileStyle(extras.ion.defaultStyle);
}
// Hide the Cesium tileset visually but allow it to be clickable
tileset.show = true;
// Set the tileset to fully transparent
tileset.style = new Cesium.Cesium3DTileStyle({
color: "rgba(0, 0, 0, 0.0)" // Fully transparent
});
tileset.loadProgress.addEventListener((numberOfPendingRequests, numberOfTilesProcessing) => {
if (numberOfPendingRequests === 0 && numberOfTilesProcessing === 0) {
// Set the tileset to fully transparent
tileset.style = new Cesium.Cesium3DTileStyle({
color: "rgba(0, 0, 0, 0.01)" // Fully transparent
});
// All tiles are loaded
tileset.show = true;
}
});
} catch (error) {
console.log(`Failed to load Cesium tileset: ${error}`);
}
}
createCesiumTileset();
// Load in Austin housing
let housingData = [];
Papa.parse('austinHousingData.csv', {
header: true,
dynamicTyping: true,
complete: function(results) {
console.log("Completed parsing CSV");
housingData = results.data;
console.log(results);
},
error: function(error, file) {
console.log("Error while parsing CSV", error, file);
},
download: true // If the file is to be fetched from the server
});
let previouslySelectedFeature; // Store the previously selected feature
const defaultColor = new Cesium.Color(1, 1, 1, 1); // Default color (white)
const highlightColor = new Cesium.Color(0.7, 0.7, 0, 1); // Highlight color (yellow)
const selectedEntity = new Cesium.Entity();
function getCesium3DTileFeatureDescription(feature) {
let html = "";
try {
if (feature && typeof feature.getPropertyIds === 'function') {
const propertyIds = feature.getPropertyIds();
propertyIds.forEach(function (propertyId) {
const value = feature.getProperty(propertyId);
if (defined(value)) {
html += `<tr><th>${propertyId}</th><td>${value}</td></tr>`;
}
});
} else if (feature && typeof feature.getProperty === 'function') {
// Fallback: try common properties
const commonProps = ['name', 'addr:street', 'addr:city', 'addr:state', 'website'];
commonProps.forEach(function(propertyId) {
try {
const value = feature.getProperty(propertyId);
if (defined(value)) {
html += `<tr><th>${propertyId}</th><td>${value}</td></tr>`;
}
} catch (error) {
// Skip this property if it causes an error
}
});
}
} catch (error) {
console.warn('Error accessing feature properties in getCesium3DTileFeatureDescription:', error);
html = '<tr><th>Error</th><td>Unable to load feature properties</td></tr>';
}
if (html.length > 0) {
html = `<table class="cesium-infoBox-defaultTable"><tbody>${html}</tbody></table>`;
}
return html;
}
function defined(value) {
return value !== undefined && value !== null;
}
function getCesium3DTileFeatureName(feature) {
let possibleIds = []; // Initialize as an empty array
// Check if feature has getPropertyIds method (for compatibility)
if (feature && typeof feature.getPropertyIds === 'function') {
try {
const propertyIds = feature.getPropertyIds();
for (let i = 0; i < propertyIds.length; i++) {
const propertyId = propertyIds[i];
if (/^name$/i.test(propertyId)) {
possibleIds[0] = feature.getProperty(propertyId);
} else if (/name/i.test(propertyId)) {
possibleIds[1] = feature.getProperty(propertyId);
}
}
} catch (error) {
console.warn('Error accessing feature properties:', error);
}
} else {
// Fallback: try common property names directly
try {
if (feature && typeof feature.getProperty === 'function') {
// Try common name properties
const commonNameProps = ['name', 'Name', 'NAME', 'title', 'Title'];
for (let i = 0; i < commonNameProps.length; i++) {
const value = feature.getProperty(commonNameProps[i]);
if (value) {
possibleIds[i] = value;
break;
}
}
}
} catch (error) {
console.warn('Error accessing feature property:', error);
}
}
// Try to assemble the street address, if possible
try {
const houseNumber = feature.getProperty('addr:housenumber');
const street = feature.getProperty('addr:street');
if (houseNumber && street) {
possibleIds[2] = `${houseNumber} ${street}`;
}
} catch (error) {
console.warn('Error accessing address properties:', error);
}
// Assemble latitude-longitude string
try {
const latitude = feature.getProperty('cesium#latitude');
const longitude = feature.getProperty('cesium#longitude');
if (latitude && longitude) {
possibleIds[3] = `${latitude}, ${longitude}`;
}
} catch (error) {
console.warn('Error accessing coordinate properties:', error);
}
// Return the first non-null, non-empty string from the possibleIds array
for (const id of possibleIds) {
if (defined(id) && id !== '') {
return id;
}
}
return "Unnamed Feature";
}
function formatFeatureForSidebar(feature) {
console.log(feature);
// Check if this is a 3D tile feature or other type of object
const is3DTileFeature = feature && typeof feature.getProperty === 'function';
const isBillboard = feature && feature.primitive && feature.id;
// Initialize variables with defaults
let name = "";
let city = "";
let houseNumber = "";
let state = "";
let street = "";
let postcode = "";
let website = "";
let wikipedia = "";
let phone = "";
let lat = "";
let lon = "";
// Handle different feature types
if (is3DTileFeature) {
try {
// Log all properties to the console if getPropertyIds is available
if (typeof feature.getPropertyIds === 'function') {
const propertyIds = feature.getPropertyIds();
for (let i = 0; i < propertyIds.length; i++) {
const propertyId = propertyIds[i];
console.log(`${propertyId}: ${feature.getProperty(propertyId)}`);
}
}
// Extract the relevant feature properties with error handling
name = feature.getProperty("name") || "";
city = feature.getProperty("addr:city") || "";
houseNumber = feature.getProperty("addr:housenumber") || "";
state = feature.getProperty("addr:state") || "";
street = feature.getProperty("addr:street") || "";
postcode = feature.getProperty("addr:postcode") || "";
website = feature.getProperty("website") || "";
wikipedia = feature.getProperty("wikipedia") || "";
phone = feature.getProperty("phone") || "";
lat = feature.getProperty("cesium#latitude") || "";
lon = feature.getProperty("cesium#longitude") || "";
} catch (error) {
console.warn('Error accessing feature properties in formatFeatureForSidebar:', error);
}
} else if (isBillboard && feature.id) {
// Handle billboard/entity features
try {
name = feature.id.name || "Map Feature";
if (feature.id.position) {
const cartographic = Cesium.Cartographic.fromCartesian(feature.id.position._value || feature.id.position);
lat = Cesium.Math.toDegrees(cartographic.latitude).toFixed(6);
lon = Cesium.Math.toDegrees(cartographic.longitude).toFixed(6);
}
} catch (error) {
console.warn('Error extracting billboard properties:', error);
name = "Map Feature";
}
} else {
// Fallback for unknown feature types
name = "Unknown Feature";
console.warn('Unknown feature type:', feature);
}
// Initialize variables for display
let displayText = "";
let address = "";
// Formulate displayText and address based on available data
let addressParts = [houseNumber, street, city, state, postcode].filter(Boolean);
if (name) {
displayText = name;
address = addressParts.join(", ");
} else if (addressParts.length > 0) {
displayText = addressParts.join(", ");
address = `${lat}, ${lon}`;
} else if (lat && lon) {
displayText = `${lat}, ${lon}`;
address = "";
}
// Continue as before ...
let description = "";
if (website) {
description += `<a href="${website}" target="_blank">Website</a><br>`;
}
if (wikipedia) {
description += `<a href="https://en.wikipedia.org/wiki/${wikipedia.split(':').pop()}" target="_blank">Wikipedia</a><br>`;
}
if (phone) {
description += `Phone: ${phone}<br>`;
}
const eventDiv = document.createElement('div');
eventDiv.className = 'list-element';
const textDiv = document.createElement('div');
textDiv.className = 'list-text';
const nameP = document.createElement('p');
nameP.className = 'list-name';
nameP.textContent = displayText;
const addressP = document.createElement('p');
addressP.className = 'list-address';
addressP.textContent = address;
const descriptionP = document.createElement('p');
descriptionP.className = 'list-description';
descriptionP.innerHTML = description;
textDiv.appendChild(nameP);
textDiv.appendChild(addressP);
textDiv.appendChild(descriptionP);
eventDiv.appendChild(textDiv);
// ... (Your image related code)
return eventDiv;
}
// function populateAndOpenSidebar(feature, sidebarPaneId) {
// const sidebarPane = document.getElementById(sidebarPaneId);
// const formattedContent = formatFeatureForSidebar(feature);
// sidebarPane.appendChild(formattedContent);
// }
function populateAndOpenSidebar(pickedFeature, sidebarPaneId) {
// Safety check for pickedFeature
if (!pickedFeature) {
console.warn('No feature provided to populateAndOpenSidebar');
return;
}
// Check if this is a 3D tile feature or other type of object
const is3DTileFeature = pickedFeature && typeof pickedFeature.getProperty === 'function';
const isBillboard = pickedFeature && pickedFeature.primitive && pickedFeature.id;
console.log('Feature type - 3D Tile:', is3DTileFeature, 'Billboard/Entity:', isBillboard);
$('#sidebar').removeClass('collapsed');
// Use property names as the sidebar title (with error handling)
try {
let featureName = "Selected Feature";
if (is3DTileFeature) {
featureName = getCesium3DTileFeatureName(pickedFeature) || "3D Building";
} else if (isBillboard && pickedFeature.id && pickedFeature.id.name) {
featureName = pickedFeature.id.name;
} else if (isBillboard) {
featureName = "Map Feature";
}
document.getElementsByClassName("cesium-geocoder-input")[0].value = featureName;
} catch (error) {
console.warn('Error getting feature name:', error);
document.getElementsByClassName("cesium-geocoder-input")[0].value = "Selected Feature";
}
// Remove the current active class from all sidebar panes
let sidebarPanes = document.getElementsByClassName('sidebar-pane');
for (let i = 0; i < sidebarPanes.length; i++) {
sidebarPanes[i].className = 'sidebar-pane';
}
// Activate the target sidebar pane
const targetSidebarPane = document.getElementById('event');
targetSidebarPane.className = 'sidebar-pane active';
// Clear the target sidebar pane
// targetSidebarPane.innerHTML = '<h1 class="sidebar-header">Feature Information</h1>';
targetSidebarPane.innerHTML = '<h1 class="sidebar-header"></h1>';
// add image to event div
var eventImage = document.createElement('img');
// eventImage.src = 'https://perfume-proceed-photo-fifth.trycloudflare.com/30.37934_-97.66141.png';
// Safely get coordinates with error handling
let latitude = '';
let longitude = '';
try {
if (pickedFeature && typeof pickedFeature.getProperty === 'function') {
latitude = pickedFeature.getProperty('cesium#latitude') || '';
longitude = pickedFeature.getProperty('cesium#longitude') || '';
}
} catch (error) {
console.warn('Error getting coordinates from feature:', error);
}
if (latitude && longitude) {
eventImage.src = 'https://imagery.austindigitaltwin.com/image/' + latitude + '/' + longitude;
} else {
eventImage.src = 'https://placehold.co/512';
}
eventImage.onerror = function() {
eventImage.src = 'https://placehold.co/512';
}
eventImage.style = 'width:100%;object-fit: cover;height:320px;';
eventImage.id = 'eventimage';
document.getElementById('event').appendChild(eventImage);
// Populate the sidebar with feature information
// const featureDescription = getCesium3DTileFeatureDescription(pickedFeature);
// const featureInfoDiv = document.createElement('div');
// featureInfoDiv.innerHTML = featureDescription;
// targetSidebarPane.appendChild(featureInfoDiv);
const formattedContent = formatFeatureForSidebar(pickedFeature);
targetSidebarPane.appendChild(formattedContent);
// Create back button div wrapper
const backButtonDiv = document.createElement("div");
backButtonDiv.className = "back-button-div tooltip";
backButtonDiv.style = "top: 3px;opacity: 1;left: 10px;border: none;";
// Create back button SVG element
const backButtonSVG = document.createElementNS("http://www.w3.org/2000/svg", "svg");
backButtonSVG.setAttribute("width", "32");
backButtonSVG.setAttribute("height", "32");
backButtonSVG.setAttribute("viewBox", "0 0 32 32");
const backPath = document.createElementNS("http://www.w3.org/2000/svg", "path");
backPath.setAttribute("d", "M20 8 L8 16 L20 24");
backPath.setAttribute("stroke", "#666");
backPath.setAttribute("stroke-width", "3");
backPath.setAttribute("fill", "#666");
backButtonSVG.appendChild(backPath);
backButtonDiv.appendChild(backButtonSVG);
// Create back button tooltip
const backButtonTooltip = document.createElement("span");
backButtonTooltip.className = "tooltiptext tooltip-bottom";
backButtonTooltip.textContent = "Back";
backButtonDiv.appendChild(backButtonTooltip);
// Add back button to DOM
const geocoderInput = document.querySelector('.cesium-geocoder-input');
// Only add the back button if it doesn't already exist
// geocoderInput.parentNode.insertBefore(backButtonDiv, geocoderInput);
if(!document.querySelector('.back-button-div')) {
geocoderInput.parentNode.insertBefore(backButtonDiv, geocoderInput);
}
// Adjust geocoder input
geocoderInput.style = "margin-left: 15px;width: 235px !important;";
// Add back button click event
backButtonDiv.addEventListener('click', function() {
// Restore original geocoder input style
geocoderInput.style = "";
// Remove the back button
backButtonDiv.remove();
document.getElementsByClassName("cesium-geocoder-input")[0].value = "";
// Restore the original active sidebar pane
for (let i = 0; i < sidebarPanes.length; i++) {
sidebarPanes[i].className = 'sidebar-pane';
}
document.getElementById(sidebarPaneId).className = 'sidebar-pane active';
});
}
// Get default left click handler for when a feature is not picked on left click
const clickHandler = viewer.screenSpaceEventHandler.getInputAction(
Cesium.ScreenSpaceEventType.LEFT_CLICK
);
let previouslySelectedBillboard; // to keep track of previously added billboard
// Your existing click event handler, modified to use the helper functions
viewer.screenSpaceEventHandler.setInputAction(function onLeftClick(movement) {
// Reset the color of the previously selected feature
if (previouslySelectedFeature) {
//previouslySelectedFeature.color = defaultColor;
}
// Temporarily hide the Google Earth 3D tileset
if (googleTileset) {
googleTileset.show = false;
}
if (cesiumTileset) {
cesiumTileset.show = true;
}
// Attempt to pick from the Cesium tileset
let pickedFeature = viewer.scene.pick(movement.position);
// Restore visibility to the Google Earth 3D tileset
if (cesiumTileset) {
// cesiumTileset.show = false;
}
if (googleTileset) {
googleTileset.show = true;
}
if (!Cesium.defined(pickedFeature) && googleTileset) {
// Just do default behavior if nothing was picked
clickHandler(movement);
return;
// pickedFeature = viewer.scene.pick(movement.position);
}
if (Cesium.defined(pickedFeature)) {
console.log("Feature picked!");
console.log(pickedFeature);
// Detect if fire, building, air sensor, crime.?
// Use the Cesium open-source helper functions to get the name and description
// const featureName = getCesium3DTileFeatureName(pickedFeature);
// const featureDescription = getCesium3DTileFeatureDescription(pickedFeature);
// Update the selected entity
// viewer.selectedEntity = new Cesium.Entity({
// name: featureName,
// description: featureDescription
// });
let sidebarPaneId = document.getElementsByClassName('sidebar-pane active')[0].id;
populateAndOpenSidebar(pickedFeature, sidebarPaneId);
// Highlight the selected feature
// pickedFeature.color = highlightColor;
// Update the reference to the previously selected feature
previouslySelectedFeature = pickedFeature;
// Put a marker down in the middle of the selected feature
// Extract the latitude and longitude properties from the picked feature
let lat = 0;
let lon = 0;
try {
if (pickedFeature && typeof pickedFeature.getProperty === 'function') {
lat = parseFloat(pickedFeature.getProperty('cesium#latitude')) || 0;
lon = parseFloat(pickedFeature.getProperty('cesium#longitude')) || 0;
}
} catch (error) {
console.warn('Error getting coordinates for marker:', error);
}
// Convert the latitude and longitude to Cartesian3 position
const position = Cesium.Cartesian3.fromDegrees(lon, lat);
// If there was a previously added billboard, remove it
if (previouslySelectedBillboard) {
viewer.entities.remove(previouslySelectedBillboard);
}
// Add a new billboard at the picked feature's position
previouslySelectedBillboard = viewer.entities.add({
position: position,
billboard: {
image: './circle.png', // Path to your marker image,
scale: 0.05, // This will need to be adjusted
verticalOrigin: Cesium.VerticalOrigin.BOTTOM
}
});
let foundHouse = null;
let address = ""; // Initialize address variable
try {
// Try to extract address with error handling
if (pickedFeature && typeof pickedFeature.getProperty === 'function') {
const houseNumber = pickedFeature.getProperty("addr:housenumber") || "";
const street = pickedFeature.getProperty("addr:street") || "";
address = `${houseNumber} ${street}`.trim();
}
console.log("Extracted address: " + address);
// Search by address
if (address && address.length > 0) {
foundHouse = housingData.find(house => house.streetAddress === address);
}
} catch (err) {
// Address not available, proceed to search by latitude and longitude
console.warn('Error extracting address:', err);
}
if (!foundHouse) {
// Search by latitude and longitude
foundHouse = housingData.find(house =>
Math.abs(house.latitude - lat) < 0.0005 &&
Math.abs(house.longitude - lon) < 0.0005
);
}
if (foundHouse) {
console.log("Found house!");
// Reference to the existing image element
const eventImage = document.getElementById('eventimage');
// Store the current image source before attempting to switch
const originalImageSrc = eventImage.src;
// Try to switch out the image to the Zillow one
const newImageSrc = `https://imagery.austindigitaltwin.com/homeImage/${foundHouse.homeImage}`;
eventImage.src = newImageSrc;
eventImage.onerror = function() {
// Revert to the original image if the new one fails to load
eventImage.src = originalImageSrc;
};
// Create HTML elements to display additional house info
const additionalInfoDiv = document.createElement('div');
additionalInfoDiv.className = 'list-element'; // Added class
const textDiv = document.createElement('div');
textDiv.className = 'list-text'; // Added class
const additionalInfoHeader = document.createElement('h2');
additionalInfoHeader.className = 'list-name'; // Added class
additionalInfoHeader.textContent = "Additional Information";
const formattedPrice = parseFloat(foundHouse.latestPrice).toLocaleString('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 0,
maximumFractionDigits: 0
});
const priceP = document.createElement('p');
priceP.className = 'list-description'; // Added class
priceP.textContent = `Price: ${formattedPrice}`;
const bedroomsP = document.createElement('p');
bedroomsP.className = 'list-description'; // Added class
bedroomsP.textContent = `Bedrooms: ${foundHouse.numOfBedrooms}`;
const bathroomsP = document.createElement('p');
bathroomsP.className = 'list-description'; // Added class
bathroomsP.textContent = `Bathrooms: ${foundHouse.numOfBathrooms}`;
// Assemble the elements
textDiv.appendChild(additionalInfoHeader);
textDiv.appendChild(priceP);
// Add lot size information
const lotSizeP = document.createElement('p');
lotSizeP.className = 'list-description'; // Added class
lotSizeP.style = 'float: right;'; // Float it to the right
const lotSizeSqFt = foundHouse.lotSizeSqFt.toLocaleString('en-US'); // Format the lot size
lotSizeP.innerHTML = `${lotSizeSqFt} ft<sup>2</sup>`; // Using HTML sup tag for square symbol
textDiv.appendChild(lotSizeP); // Append the lot size element
lotSizeP.style.margin = '0px';
priceP.style.margin = '0px';
textDiv.appendChild(bedroomsP);
textDiv.appendChild(bathroomsP);
additionalInfoDiv.appendChild(textDiv);
// Add homeType information
const homeTypeP = document.createElement('p');
homeTypeP.className = 'list-description'; // Added class
homeTypeP.textContent = foundHouse.homeType;
homeTypeP.style = 'float: right; font-size: small;';
additionalInfoHeader.appendChild(homeTypeP);
// Append additional information to sidebar
const targetSidebarPane = document.getElementById('event');
targetSidebarPane.appendChild(additionalInfoDiv);
}
{
// ... Existing code above the additional information ...
// ... Existing code for additional information ...
// Function to create stats section
// Generate random numbers for crimes and fires (0 to 2)
let randomCrimeCount = Math.floor(Math.random() * 3);
let randomFireCount = Math.floor(Math.random() * 3);
// Create parent div for stats
let statsDiv = document.createElement('div');
statsDiv.className = 'event-stats';
// Create individual stat boxes
let crimeBox = document.createElement('div');
crimeBox.className = 'stat-box';
let fireBox = document.createElement('div');
fireBox.className = 'stat-box';
// Create progress ring divs
let crimeRing = document.createElement('div');
crimeRing.className = 'progress-ring';
let fireRing = document.createElement('div');
fireRing.className = 'progress-ring';
// Assign risk level classes based on random numbers (for demonstration)
crimeRing.classList.add(randomCrimeCount === 0 ? 'low-risk' : randomCrimeCount === 1 ? 'medium-risk' : 'high-risk');
fireRing.classList.add(randomFireCount === 0 ? 'low-risk' : randomFireCount === 1 ? 'medium-risk' : 'high-risk');
// Create icons and numbers
let crimeIcon = document.createElement('img');
crimeIcon.src = 'crime.png'; // Path to your crime icon
let fireIcon = document.createElement('img');
fireIcon.src = 'firelogo.png'; // Path to your fire icon
let crimeNumber = document.createElement('p');
// crimeNumber.innerText = randomCrimeCount;
let fireNumber = document.createElement('p');
// fireNumber.innerText = randomFireCount;
// Assemble everything
crimeBox.appendChild(crimeRing);
crimeBox.appendChild(crimeIcon);
crimeBox.appendChild(crimeNumber);
fireBox.appendChild(fireRing);
fireBox.appendChild(fireIcon);
fireBox.appendChild(fireNumber);
statsDiv.appendChild(crimeBox);
statsDiv.appendChild(fireBox);
// Append stats to target sidebar
const targetSidebarPane = document.getElementById('event');
// Put stats-div inside a list-element div
let statsWrapper = document.createElement('div');
statsWrapper.className = 'list-element';
statsWrapper.appendChild(statsDiv);
statsWrapper.style.display = 'block';
statsWrapper.style.padding = '40px';
targetSidebarPane.appendChild(statsWrapper);
}
} else {
console.log("No feature picked.");
}
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
function addMore() {
console.log("hey")
var moreButton = document.getElementById("moreButton");
if(moreButton.textContent == "More...") {
document.getElementById("more").style.display = "block";
document.getElementById("moreButton").textContent = "Less...";
} else {
document.getElementById("more").style.display = "none";
document.getElementById("moreButton").textContent = "More...";
}
}
async function plotPoint(tileset, lat, lng, fireData) {
console.log(tileset, lat, lng, fireData)
const position = Cesium.Cartesian3.fromDegrees(lng, lat, 10000); // Assume initial altitude of 10,000m
const ray = new Cesium.Ray(position, Cesium.Cartesian3.negate(Cesium.Cartesian3.fromDegrees(lng, lat), new Cesium.Cartesian3()));
const intersection = viewer.scene.pickFromRay(ray, [tileset]);
if (Cesium.defined(intersection)) {
const clampPosition = intersection.position;
clampPosition.z -= 30;
clampPosition.y += 30;
clampPosition.x += 20;
let billboardEntity = viewer.entities.add({
position: clampPosition,
billboard: {
image: 'https://raw.githubusercontent.com/urbaninfolab/FireIncidentFrontend/main/assets/images/fire.png',
scale: 0.1,
pixelSize: 10,
outlineWidth: 3,
verticalOrigin: Cesium.VerticalOrigin.CENTER,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
},
// Store the fire data in the entity
fireEventData: fireData
});
let billboardId = billboardEntity.id;
const action = {
remove: (popup) => {
console.log(popup, "The popup was removed");
// Translate to english: "The popup was removed"
},
onChange: (popup) => {
console.log(popup, "The popup was moved");
// Translate to english: "The popup was moved"
},
editAttr: (popup) => {
console.log(popup, "The popup needs to edit attributes!");
// Translate to english: "The popup needs to edit attributes"
popup.setContent("My content has been changed!")
// Translate to english: "My content has been changed!"
}
}
console.log(fireData);
let link = fireData.link;
let longNLatString = link.replace('http://maps.google.com/maps?q=', '');
url = 'https://api.weather.gov/points/' + longNLatString;
var response = await fetch(url);
var api = await response.json();
var hourlyApiUrl = api.properties.forecastHourly;
var response = await fetch(hourlyApiUrl);
var hourlyData = await response.json();
hourlyData1 = hourlyData.properties.periods[0];
let handler = new Cesium.ScreenSpaceEventHandler(viewer.canvas);
handler.setInputAction(function(click) {
let pickedObject = viewer.scene.pick(click.position);
if (Cesium.defined(pickedObject) && Cesium.defined(pickedObject.id) && pickedObject.id.id === billboardId) {
// Use the same logic as the fires list
const fireEvent = pickedObject.id.fireEventData;
if (fireEvent) {
// Calculate coordinates for image
let imgLat, imgLng;
if (fireEvent.link) {
let lat_lng = fireEvent.link.replace('http://maps.google.com/maps?q=', '').split(',');
imgLat = parseFloat(lat_lng[0]).toFixed(5);
imgLng = parseFloat(lat_lng[1]).toFixed(5);
} else if (fireEvent.latitude && fireEvent.longitude) {
imgLat = fireEvent.latitude.toFixed(5);
imgLng = fireEvent.longitude.toFixed(5);
}
// Call the shared fire event click handler (defined in main.js)
if (typeof handleFireEventClick === 'function') {
handleFireEventClick(fireEvent, imgLat, imgLng, null);
} else {
console.warn('handleFireEventClick function not available');
}
}
}
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
} else {
console.log('No intersection found');
// Do it again in 1 second
try{
setTimeout(() => plotPoint(tileset, lat, lng, fireData), 1000);
}catch(err){
console.log(err);
}
}
}
function fetchAllData() {
fetch('https://raw.githubusercontent.com/urbaninfolab/FireIncidentData/master/api/v1/Austin/2022/08/08/FireMap.json')
.then(response => response.json())
.then(data => {
let items = data.rss.channel.item;
console.log(items);
for (let item of items) {
let link = item.link;
console.log(link);
let latLng = link.replace("http://maps.google.com/maps?q=", "");
let [lat, lng] = latLng.split(",");
console.log(lat, lng);
try{
plotPoint(window.tileset, parseFloat(lat), parseFloat(lng), item);
}catch(err){
console.log(err);
}
let modelUrl = `${latLng}.glb`;
let position = Cesium.Cartesian3.fromDegrees(parseFloat(lng), parseFloat(lat));
let offset = new Cesium.Cartesian3(-250, -80, -200);
let finalPosition = Cesium.Cartesian3.add(position, offset, new Cesium.Cartesian3());
let hpr = new Cesium.HeadingPitchRoll(Cesium.Math.toRadians(90), Cesium.Math.toRadians(0), Cesium.Math.toRadians(0));
let orientation = Cesium.Transforms.headingPitchRollQuaternion(finalPosition, hpr);
viewer.entities.add({
position : finalPosition,
orientation : orientation,
model : {
uri : modelUrl,