connectToAPI.js 17.2 KB
Newer Older
JOE Thunyathep S's avatar
update  
JOE Thunyathep S committed
1
var coordinatesBB = []
BujarMuharemi's avatar
BujarMuharemi committed
2
//var url = "https://simstadt-api.iaf-ex.hft-stuttgart.de:8080/workflow/execute" //old link
3
4
var url = "http://vm24.fkc.hft-stuttgart.de:8082/workflow/execute" // URL to API
var url2 = "http://vm24.fkc.hft-stuttgart.de:8082/workflow/timedShadowValueByDay/"
5
6
var pvURL = "http://vm24.fkc.hft-stuttgart.de:8082/workflow/readPVPotential"

7
8
9
/*TODO#1:   -get current data from the api and create local test data (apiData foler)
            -add connection handeling  (error messages when there isnt a connection and then using the local test data)
*/
10
11
var localShadowData = "/public/test/APIdata/shadowData.json"
var localPvpotentialData = "/public/test/APIdata/buildingInformation.json"
JOE Thunyathep S's avatar
update  
JOE Thunyathep S committed
12
13
14
15
16
17
18
19

var buildingFunctionSort
var constructionYearSortPick
var heightSortPick
var heatedVolumeSortPick
var totalSurfaceAreaSortPick
var roofTypeSortPick
var uValueSortPick
Izairi's avatar
Izairi committed
20
var shadowdata
21

22

23
async function fetchPvPotentialJSON() {
24
25
26
27
28
    var bottomLat = coordinatesBB[1]
    var leftLng = coordinatesBB[0]
    var rightLng = coordinatesBB[2]
    var topLat = coordinatesBB[3]

29
    const response = await fetch(pvURL, {
30
31
32
33
        method: "POST",
        body: JSON.stringify({
            "boundingBox": {
                "bottomLat": bottomLat, //48.779004965,
34
                "leftLng": leftLng, //9.1686843081,
35
                "lodType": "LOD2",
36
37
38
39
                "rightLng": rightLng, //9.175336684,
                "topLat": topLat //48.7822869656
            },
            "cityGMLRef": "campusLOD2"
40
41
42
43
44
45
46
47
48
49
50
        }),
        headers: {
            "Content-Type": "application/json",
            "Authorization": "Basic YWRtaW46YWRtaW4xMjM="
        }
    })

    const data = await response.json();
    return data
}

51
52
53
54
async function fetchshadowDataJSON() {
    var bottomLat = coordinatesBB[1]
    var leftLng = coordinatesBB[0]
    var rightLng = coordinatesBB[2]
55
    var topLat = coordinatesBB[3] //
56
    var day = "1";
57
    const response = await fetch(url2 + day, {
58
59
60
61
        method: "POST",
        body: JSON.stringify({
            "boundingBox": {
                "bottomLat": bottomLat, //48.779004965,
62
                "leftLng": leftLng, //9.1686843081,
63
                "lodType": "LOD2",
64
65
                "rightLng": rightLng, //9.175336684,
                "topLat": topLat //48.7822869656
66
67
68
69
70
71
72
73
            },
            "cityGMLRef": "campusLOD2"
        }),
        headers: {
            "Content-Type": "application/json",
            "Authorization": "Basic YWRtaW46YWRtaW4xMjM="
        }
    })
74
75

    const data = await response.json();
76
77
78
    return data
}

79

JOE Thunyathep S's avatar
update  
JOE Thunyathep S committed
80
81
82
83
async function fetchDataJSON() {
    var bottomLat = coordinatesBB[1]
    var leftLng = coordinatesBB[0]
    var rightLng = coordinatesBB[2]
84
    var topLat = coordinatesBB[3] //
JOE Thunyathep S's avatar
update  
JOE Thunyathep S committed
85

86
    const response = await fetch(url, {
JOE Thunyathep S's avatar
update  
JOE Thunyathep S committed
87
88
89
90
        method: "POST",
        body: JSON.stringify({
            "boundingBox": {
                "bottomLat": bottomLat, //48.779004965,
91
                "leftLng": leftLng, //9.1686843081,
JOE Thunyathep S's avatar
update  
JOE Thunyathep S committed
92
                "lodType": "LOD2",
93
94
                "rightLng": rightLng, //9.175336684,
                "topLat": topLat //48.7822869656
JOE Thunyathep S's avatar
update  
JOE Thunyathep S committed
95
            },
BujarMuharemi's avatar
BujarMuharemi committed
96
            "cityGMLRef": "campusLOD2",
JOE Thunyathep S's avatar
update  
JOE Thunyathep S committed
97
98
99
100
101
102
103
            "interestedAttributes": [
                "uValue",
                "volume",
                "height",
                "heatedVolume",
                "yearOfConstruction",
                "buildingFunction",
104
105
                "monthlyHeating",
                "monthlyCooling",
JOE Thunyathep S's avatar
update  
JOE Thunyathep S committed
106
107
                "pvPotential",
                "roofType",
108
                "totalSurfaceArea"
JOE Thunyathep S's avatar
update  
JOE Thunyathep S committed
109
110
111
112
113
114
115
116
117
118
119
120
121
            ],
            "properies": {
                "physicsUseScenario": false
            }
        }),
        headers: {
            "Content-Type": "application/json",
            "Authorization": "Basic YWRtaW46YWRtaW4xMjM="
        }
    })
    const data = await response.json()
    return data
}
122

JOE Thunyathep S's avatar
update  
JOE Thunyathep S committed
123
124
document.getElementById("loader").style.visibility = "hidden"

125
async function getLocalShadowdata() {
126
    // gets the response from localShadowData and put it inside a constant
127
128
    const response = await fetch(localShadowData);
    //the response have to be converted to json type file, so it can be used
129
    const data = await response.json();
130
131
    console.log(data)
    return data;
132
}
133

134
async function processData() {
JOE Thunyathep S's avatar
update  
JOE Thunyathep S committed
135
136
    console.log(coordinatesBB)
    console.log("Waiting for data....")
137
    shadowdata= await getLocalShadowdata()
138

139
    timeout(25000, getLocalShadowdata()).then((response) => {
140
141
142
        console.log(response)
        shadowdata = response;
    }).catch((error) => { //catching the error(no connection)/ timeout and displaying an alert for the user
143
        console.log(shadowdata);
144
        //loadLocalAPIshadowData here...
145
    })
146

147
148
149
    timeout(10000, fetchPvPotentialJSON()).then((response) => {
        console.log(response)
    }).catch((error) => {
150
        console.log(error)
151
152
153
154
155
156
    })


    timeout(10000, fetchDataJSON()).then((response) => {
        calculateData(response);
    }).catch((error) => {
157
        console.log(error)
158
        
159
        fetch(localPvpotentialData)
Kolokolnikova's avatar
Kolokolnikova committed
160
161
        .then(response => response.text())
        .then(text => calculateData( JSON.parse(text)))
162
        
Kolokolnikova's avatar
Kolokolnikova committed
163
    })
164
165


166
167


Kolokolnikova's avatar
Kolokolnikova committed
168
}
JOE Thunyathep S's avatar
update  
JOE Thunyathep S committed
169
170
171



172
function calculateData(data) {
Kolokolnikova's avatar
Kolokolnikova committed
173
174
175
176
    console.log(data);
    document.getElementById("cesiumContainer").style.opacity = "1";
    document.getElementById("loader").style.visibility = "hidden"
    console.log("....received data")
JOE Thunyathep S's avatar
update  
JOE Thunyathep S committed
177

Kolokolnikova's avatar
Kolokolnikova committed
178
    var buildingsMAP = new Map()
JOE Thunyathep S's avatar
update  
JOE Thunyathep S committed
179

Kolokolnikova's avatar
Kolokolnikova committed
180
    data.buildings.forEach(bu => {
JOE Thunyathep S's avatar
update  
JOE Thunyathep S committed
181

Kolokolnikova's avatar
Kolokolnikova committed
182
183
        var partsArray = []
        var surefacesArray = []
JOE Thunyathep S's avatar
update  
JOE Thunyathep S committed
184

Kolokolnikova's avatar
Kolokolnikova committed
185
186
187
188
189
        bu.parts.forEach(p =>
            p.surfaces.forEach(s =>
                surefacesArray.push(new Surface(s.id,
                    s.attributes.uValue,
                    s.attributes.totalSurfaceArea))))
JOE Thunyathep S's avatar
update  
JOE Thunyathep S committed
190

Kolokolnikova's avatar
Kolokolnikova committed
191
192
193
194
195
196
197
198
199
200
201
        bu.parts.forEach(p => partsArray.push(new Part(p.id,
            surefacesArray,
            p.attributes.volume,
            p.attributes.height,
            p.attributes.heatedVolume,
            p.attributes.yearOfConstruction,
            p.attributes.buildingFunction,
            p.attributes.monthlyHeating,
            p.attributes.monthlyCooling,
            p.attributes.roofType)))

202
        buildingsMAP.set(bu.id, new Building(bu.id, partsArray)) //puts buildings with parts and surfaces in a map
Kolokolnikova's avatar
Kolokolnikova committed
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

    })

    var partHeightMAP = new Map()
    var partVolumeMAP = new Map()
    var partHeatedVolumeMAP = new Map()
    var partConstructionYearMAP = new Map()
    var partBuildingTypeMAP = new Map()
    var partMonthlyHeatingMAP = new Map()
    var partMonthlyCoolingMAP = new Map()
    var surfaceUValueMAP = new Map()
    var partRoofTypeMAP = new Map()
    var surfaceTotalSurfaceAreaMAP = new Map()

    //fill height, heated volume and construction year map
    buildingsMAP.forEach(b => {
        b.parts.forEach(part => {
            if (part.height !== undefined) {
                partHeightMAP.set(part.id, part.height)
            }
            if (part.volume !== undefined) {
                partVolumeMAP.set(part.id, part.volume)
            }
            if (part.heatedVolume !== undefined) {
                partHeatedVolumeMAP.set(part.id, part.heatedVolume)
            }
            if (part.yearOfConstruction !== undefined && part.yearOfConstruction <= "2020") {
                partConstructionYearMAP.set(part.id, part.yearOfConstruction)
            }
            if (part.buildingFunction !== undefined) {
                partBuildingTypeMAP.set(part.id, part.buildingFunction)
            }
            if (part.monthlyHeating !== undefined) {
                partMonthlyHeatingMAP.set(part.id, part.monthlyHeating)
            }
            if (part.monthlyCooling !== undefined) {
                partMonthlyCoolingMAP.set(part.id, part.monthlyCooling)
            }
            if (part.roofType !== undefined) {
                partRoofTypeMAP.set(part.id, part.roofType)
            }
            part.surfaces.forEach(s => {
                if (s.uValue !== undefined) {
                    surfaceUValueMAP.set(s.id, s.uValue)
JOE Thunyathep S's avatar
update  
JOE Thunyathep S committed
247
248
                }
            })
Kolokolnikova's avatar
Kolokolnikova committed
249
250
            //totalSurfaceArea
            surfaceTotalSurfaceAreaMAP.set(part.id, part.surfaces)
JOE Thunyathep S's avatar
update  
JOE Thunyathep S committed
251
        })
Kolokolnikova's avatar
Kolokolnikova committed
252
    })
JOE Thunyathep S's avatar
update  
JOE Thunyathep S committed
253

Kolokolnikova's avatar
Kolokolnikova committed
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
    //sort maps
    const heightSort = new Map([...partHeightMAP.entries()].sort((a, b) => b[1] - a[1]));
    const heatedVolumeSort = new Map([...partHeatedVolumeMAP.entries()].sort((a, b) => b[1] - a[1]));
    const constructionYearSort = new Map([...partConstructionYearMAP.entries()].sort((a, b) => a[1] - b[1]));
    const uValueSort = new Map([...surfaceUValueMAP.entries()].sort((a, b) => b[1] - a[1]));

    //for Properties Single Buildings
    buildingFunctionSortPick = new Map([...partBuildingTypeMAP.entries()].sort((a, b) => b[1] - a[1]));
    constructionYearSortPick = new Map([...partConstructionYearMAP.entries()].sort((a, b) => a[1] - b[1]));
    heightSortPick = new Map([...partHeightMAP.entries()].sort((a, b) => b[1] - a[1]));
    heatedVolumeSortPick = new Map([...partHeatedVolumeMAP.entries()].sort((a, b) => b[1] - a[1]));
    totalSurfaceAreaSortPick = new Map([...surfaceTotalSurfaceAreaMAP.entries()].sort((a, b) => b[1] - a[1]));
    roofTypeSortPick = new Map([...partRoofTypeMAP.entries()].sort((a, b) => b[1] - a[1]));
    uValueSortPick = new Map([...surfaceUValueMAP.entries()].sort((a, b) => b[1] - a[1]));


    //fill arrays needed for charts
    heightSort.forEach((value, key) => addHeightInfosToArrays(key, value))
    heatedVolumeSort.forEach((value, key) => addHeatedVolumeInfosToArrays(key, value))
    constructionYearSort.forEach((value) => yearOfConstructionValues.push(value))
    partBuildingTypeMAP.forEach((value) => buildingTypeValues.push(value))
    partMonthlyHeatingMAP.forEach((valueArray, key) => yearlyHeatingDemand(key, valueArray))
    partMonthlyCoolingMAP.forEach((valueArray, key) => yearlyCoolingDemand(key, valueArray))
    uValueSort.forEach((value, key) => {
        uValueSurfaces(key, value)
        uValuesAll.push(value)
    })
JOE Thunyathep S's avatar
update  
JOE Thunyathep S committed
281

Kolokolnikova's avatar
Kolokolnikova committed
282
283
284
    partMonthlyHeatingMAP.forEach((value, key) => addmonthlyHeatingInfosToArrays(key, value))
    partMonthlyCoolingMAP.forEach((value, key) => addmonthlyCoolingInfosToArrays(key, value))
    partVolumeMAP.forEach((value, key) => addVolumeValues(key, value))
JOE Thunyathep S's avatar
update  
JOE Thunyathep S committed
285

Kolokolnikova's avatar
Kolokolnikova committed
286
287
288
289
290
291
292
293
    //calculates year of construction frequency
    yearFrequency()

    //calculates building type frequency
    buildingTypeFrequency()

    //calculates uValue frequency
    uValueFrequency()
JOE Thunyathep S's avatar
update  
JOE Thunyathep S committed
294

Kolokolnikova's avatar
Kolokolnikova committed
295
296
297
298
299
300
301
    //sorts yearly heating & cooling demand for charts
    sortMap()

    //disables attributes in chart without values
    availableAttributes()

    //color buildings with heating demand
302
    document.getElementById("checkbox2").addEventListener("change", function() {
Kolokolnikova's avatar
Kolokolnikova committed
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
        if (this.checked) {
            tileContent.forEach(t => {
                let tileID = t.getProperty("gml_parent_id")
                let tileColor = heatingIDColorMAP.get(tileID)
                if (tileColor !== undefined) {
                    t.color = Cesium.Color.fromCssColorString(tileColor)
                } else {
                    t.color = new Cesium.Color(1, 1, 1, 1)
                }
            })
            console.log("colored")
        } else {
            tileContent.forEach(t => t.color = new Cesium.Color(1, 1, 1, 1))
            console.log("not colored")
        }
    })

    //color surfaces with uValue
321
    document.getElementById("checkbox1").addEventListener("change", function() {
Kolokolnikova's avatar
Kolokolnikova committed
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
        if (this.checked) {
            tileContent.forEach(t => {
                let tileID = t.getProperty("gml_id")
                let tileColor = surfaceIDColorMAP.get(tileID)
                if (tileColor !== undefined) {
                    t.color = Cesium.Color.fromCssColorString(tileColor)
                } else {
                    t.color = new Cesium.Color(1, 1, 1, 1)
                }
            })
            console.log("colored")
        } else {
            tileContent.forEach(t => t.color = new Cesium.Color(1, 1, 1, 1))
            console.log("not colored")
        }
JOE Thunyathep S's avatar
update  
JOE Thunyathep S committed
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
    })
}

function showAllUVales() {
    this.parts.forEach(p => p.surfaces.forEach(s => console.log(s.uValue)))
}

function Building(id, parts) {
    this.id = id
    this.parts = parts
    this.showAllUVales = showAllUVales
}

function Part(id, surfaces, volume, height, heatedVolume, yearOfConstruction, buildingFunction, monthlyHeating, monthlyCooling, roofType) {
    this.id = id;
    this.surfaces = surfaces
    this.volume = volume
    this.height = height
    this.heatedVolume = heatedVolume
    this.yearOfConstruction = yearOfConstruction
    this.buildingFunction = buildingFunction
    this.monthlyHeating = monthlyHeating
    this.monthlyCooling = monthlyCooling
    this.roofType = roofType
}

function Surface(id, uValue, totalSurfaceArea) {
    this.id = id;
    this.uValue = uValue
    this.totalSurfaceArea = totalSurfaceArea
}

let tileContent = []

// When the user clicks the button, open the modal
var elemurlevt = document.getElementById("submitID");
elemurlevt.addEventListener("click", loadTileset);

//Get the modal
var modal = document.getElementById("myModal");
var span = document.getElementsByClassName("close")[0];

//close the modal
380
span.onclick = function() {
JOE Thunyathep S's avatar
update  
JOE Thunyathep S committed
381
382
383
384
385
    modal.style.display = "none";
    deleteTilesetButtons()
}

// modal closes, when the user clicks anywhere outside of the modal
386
window.onclick = function(event) {
JOE Thunyathep S's avatar
update  
JOE Thunyathep S committed
387
388
389
390
391
392
    if (event.target == modal) {
        modal.style.display = "none";
        deleteTilesetButtons()
    }
}

BujarMuharemi's avatar
BujarMuharemi committed
393
//-------------------------------------------------------------------------------
Muharemi's avatar
Muharemi committed
394
395
var tileData = null;
var tileset = null;
Izairi's avatar
Izairi committed
396
397
398
//var tilesetURL = 'http://vm24.fkc.hft-stuttgart.de:8081/CampusLOD2Old/tileset.json';
var tilesetURL = 'http://vm24.fkc.hft-stuttgart.de:8081/CampusLOD2/tileset.json';

399
400
//var localTestTileset = '/3dclient4simstadtapi/public/test/gmlTileset_v1.json';
var localTestTileset = getAbsoulteTestPath("/test/gmlTileset_v1.json");
BujarMuharemi's avatar
BujarMuharemi committed
401
402


403
404
function timeout(ms, promise) {
    return new Promise(function(resolve, reject) {
405
406
407
408
        setTimeout(function() {
            reject(new Error("timeout"))
        }, ms)
        promise.then(resolve, reject)
409
410
    })
}
411

412

413
//fetching the tileset and handling the connection
414
415
416
417
async function fetchTileset() {
    timeout(1000, fetch(tilesetURL)).then((response) => {
        loadAndZoomToTileset(tilesetURL);
    }).catch((error) => { //catching the error(no connection)/ timeout and displaying an alert for the user
418
        //var errorString = error["stack"]+"\n"+error["message"]; // formatting the error array
419
        swal({ text: "Could not connect to Server. Using now: local data", icon: "info" });
420
        console.log("Using local test data");
421
        loadAndZoomToTileset(localTestTileset); //TODO#3: fix the link so the local tileset can be loaded
422
    })
BujarMuharemi's avatar
BujarMuharemi committed
423
}
JOE Thunyathep S's avatar
update  
JOE Thunyathep S committed
424
425


Muharemi's avatar
Muharemi committed
426

BujarMuharemi's avatar
BujarMuharemi committed
427
/*
Muharemi's avatar
Muharemi committed
428
429
430
431
432
    NOTE #1:    -load the models but the are in the too high in the "air"
                -building view doesn´t work because all buildings are grouped together
                -surfaces are also broken

            -->this fixme is the problem of the backendteam !
BujarMuharemi's avatar
BujarMuharemi committed
433
434
435
436

    ? maybe add old menu back and the option to also load the new ones 
    
*/
Muharemi's avatar
Muharemi committed
437

438
439

//loads tileset after submit button is clicked
440
function loadTileset() {
Muharemi's avatar
Muharemi committed
441
442
    viewer.scene.primitives.remove(tileset);
    tileContent = [];
JOE Thunyathep S's avatar
update  
JOE Thunyathep S committed
443
    modal.style.display = "block";
444

445
    fetchTileset();
446

447
448
    //var userurl = document.getElementById("3Durl").value;   //returns the chosen area from the dropdown    
}
Muharemi's avatar
Muharemi committed
449
//loads the tileset from the url into the cesium viewer and zooms to it
450
451
function loadAndZoomToTileset(url) {
    tileset = viewer.scene.primitives.add(new Cesium.Cesium3DTileset({
452
        url: url
BujarMuharemi's avatar
BujarMuharemi committed
453
    }));
454

455

BujarMuharemi's avatar
BujarMuharemi committed
456
    viewer.zoomTo(tileset, new Cesium.HeadingPitchRange(0, -0.5, 0));
457
458
459
    modal.style.display = "none";
    saveTilesetContent(tileset)
    deleteTilesetButtons()
JOE Thunyathep S's avatar
update  
JOE Thunyathep S committed
460
461
462
}


BujarMuharemi's avatar
BujarMuharemi committed
463
function useContent(content) {
JOE Thunyathep S's avatar
update  
JOE Thunyathep S committed
464
465
466
467
468
469
470
471
472
    content.forEach(cont => {
        var element = document.createElement("input")
        element.type = "button"
        element.value = cont.title
        element.value = cont.title
        element.name = "individualTileset"

        document.getElementById("myList").appendChild(element);

473
        element.onclick = function() {
JOE Thunyathep S's avatar
update  
JOE Thunyathep S committed
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
            tileset = viewer.scene.primitives.add(new Cesium.Cesium3DTileset({
                url: cont.href
            }));
            viewer.zoomTo(tileset, new Cesium.HeadingPitchRange(0, -0.5, 0));
            modal.style.display = "none";
            saveTilesetContent(tileset)
            deleteTilesetButtons()
        };
    })
}

function saveTilesetContent(tileset) {
    tileset.tileLoad.addEventListener(tile => {
        const content = tile.content;
        for (let i = 0; i < content.featuresLength; i++) {
            let f = content.getFeature(i);
            tileContent.push(f)
        }
    })
}

function deleteTilesetButtons() {
    var x = document.getElementsByName("individualTileset")
    var len = x.length
498

BujarMuharemi's avatar
BujarMuharemi committed
499
    //checking if there are even tileset to delete
500
    if (x.length > 0) {
BujarMuharemi's avatar
BujarMuharemi committed
501
502
503
504
        parentNode = x[0].parentNode;
        for (var i = 0; i < len; i++) {
            parentNode.removeChild(x[0]);
        }
JOE Thunyathep S's avatar
update  
JOE Thunyathep S committed
505
    }
506

JOE Thunyathep S's avatar
update  
JOE Thunyathep S committed
507
}
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522

//expects path to test data, from the 'public' folder as origin
// for example: getAbsoulteTestPath("/test/gmlTileset_v1.json")
function getAbsoulteTestPath(path){   
    var a = window.location.pathname.split("/")
    a.pop();a.reverse();a.pop();

    var path;
    a.forEach(element => path+"/"+element);
    var path = window.location.origin+"/"+a[0]+path;
    console.log(path);

    return path;
}