-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdemo_sample.html
515 lines (424 loc) · 21.6 KB
/
demo_sample.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
<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>SpeckleCon2024 GIS demo</title>
<style type="text/css">
html,body{margin:0px;height:100%;width:100%}
.container{width:100%;height:100%}
#floating-panel {
font-family: Arial, Helvetica, sans-serif;
color: rgb(54, 54, 54);
position: absolute;
width: 300px;
top: 50px;
left: 50px;
z-index: 5000;
background-color: rgb(245, 245, 245);
border: 0px solid rgb(109, 109, 109);
border-radius: 1px;
box-shadow: 5px 10px 20px #0000003c;
padding: 0px;
}
</style>
<script src="https://unpkg.com/deck.gl@latest/dist.min.js"></script>
<body>
<div id="floating-panel">
<div style="padding:7px;padding-bottom:3px;padding-left: 20px; background-color: rgb(22, 109, 231); color: white">
<h3 style="margin:0px;">Base layers</h3>
</div>
<div style="padding:10px; padding-bottom: 20px;">
<label class="switch">
<input type="checkbox" disabled="true" checked> Basemap light</input>
<span class="slider"></span>
</label><br><br>
</div>
<div style="padding:7px;padding-bottom:3px;padding-left: 20px; background-color: rgb(22, 109, 231); color: white">
<h3 style="margin:0px;">Speckle layers</h3>
</div>
<div style="padding:10px; padding-bottom: 20px;">
<label class="switch">
<input id="gis_layer" type="checkbox" disabled="true" checked> QGIS Speckle layer</input>
<span class="slider"></span>
</label><br><br>
<label class="switch">
<input id="rhino_layer" type="checkbox" disabled="true" checked> Rhino Speckle layer</input>
<span class="slider"></span>
</label><br><br>
</div>
<div style="padding:7px;padding-bottom:3px;padding-left: 20px; background-color: rgb(22, 109, 231); color: white">
<h3 style="margin:0px;">API layers</h3>
</div>
<div style="padding:10px; padding-bottom: 20px;">
<label class="switch">
<input id="traffic_layer" type="checkbox" disabled="true" checked> Traffic layer</input>
<span class="slider"></span>
</label><br><br>
</div>
</div>
<div id="map" class="container"></div>
<script>
const TRAFFIC_API_KEY = "41_ea6vX0sH8ec-wbRIEzUKt9tCUbW4rXDUeObNKoUc"
// color utils
function rgbaToArgbList(color) {
if (color == null){
return [10,132,255,255];
}
col = color.replace('rgba(','').replace(')','').split(',',4);
value = [ parseInt(col[0]), parseInt(col[1]), parseInt(col[2]), parseInt(col[3]) ];
return value;
}
function rgbaToArgbListDarker(color) {
if (color == null){
return [7,120,235,255];
}
col = color.replace('rgba(','').replace(')','').split(',',4);
value = [ parseInt(col[0])*0.5, parseInt(col[1])*0.5, parseInt(col[2])*0.5, parseInt(col[3]) ];
return value;
}
function getTrafficColor(speed_factor){
if (speed_factor>1){
speed_factor=1
}
speed_factor = (speed_factor - 0.5)*2 // remap for bigger visual difference
if (speed_factor<0){
speed_factor=0.1
}
color = 'rgba(100,100,100,255)'
green = Math.pow( (speed_factor ),0.5) *240
blue = 0
red = Math.pow( ((1 - speed_factor) ),0.5) *240
color = `rgba(${Math.round(red)},${Math.round(green)},${Math.round(blue)},255)`
return color
}
// traffic related utils
async function getFeaturesFromTraffic(traffic_url)
{
traffic_features = []
try{
const data = await fetch(traffic_url).then(response => response.json());
results = data.results
for (segm in results){
var speed_factor = results[segm].currentFlow.speed / results[segm].currentFlow.freeFlow
links = results[segm].location.shape.links
pts_coords = []
for (link_ind in links){
pts = links[link_ind].points
for (pt_ind in pts){
pt = pts[pt_ind]
pts_coords.push([pt.lng, pt.lat, 0])
}
}
lineColor = getTrafficColor(speed_factor);
new_line = {"type":"Feature",
"geometry": {"type": "LineString", "coordinates": pts_coords},
"displayProperties": {"color": lineColor } };
traffic_features.push(new_line);
}
}
catch {}
return traffic_features
}
function createTrafficLayerFromFeatures(traffic_features){
traffic_layer = new deck.GeoJsonLayer({
id: 'traffic_layer',
data: traffic_features,
getLineWidth: f => 6,
getLineColor: f => rgbaToArgbList(f.displayProperties.color),
})
return traffic_layer;
}
async function addTrafficLayer(extent, all_layers){
console.log("__update traffic")
// specify the traffic query extend a bit larger than the model extent
buffer = 0.002 // degrees, approx 200 meters
range_x = extent[2] - extent[0] + 2* buffer
range_y = extent[3] - extent[1] + 2* buffer
center_x = extent[0] + (extent[2] - extent[0])/2
center_y = extent[1] + (extent[3] - extent[1])/2
var bbox = `${center_x-range_x/2},${center_y-range_y/2},${center_x+range_x/2},${center_y+range_y/2}`
var traffic_url = `https://data.traffic.hereapi.com/v7/flow?locationReferencing=shape&in=bbox:${bbox}&apiKey=${TRAFFIC_API_KEY}`
var traffic_features = await getFeaturesFromTraffic(traffic_url);
traffic_layer = createTrafficLayerFromFeatures(traffic_features);
all_layers.push(traffic_layer);
}
// speckle data utils
function fixVerticalPolygons(speckle_data){
var speckle_features = []
for (let i = 0; i < speckle_data.features.length; i++) {
feature = speckle_data.features[i];
coords = feature.geometry.coordinates;
if (feature.geometry.type.includes("Polygon")) {
polygon_all_parts = []
// iterate through Polygon Parts
for (let p = 0; p < coords.length; p++) {
// check orientation of each PolygonPart, if vertical - shift points slightly
polygon_part = [];
inner = false;
for (let c = 0; c < coords[p].length; c++) {
polygon_part_loop = [];
if (c>0){
inner = true;
}
sum_orientation = 0;
polygon_pts = coords[p][c]; // usually 3 for Mesh faces
for (let k = 0; k < polygon_pts.length; k++){
index = k + 1
if (k == polygon_pts.length - 1){index = 0}
pt = polygon_pts[k]
pt2 = polygon_pts[index]
sum_orientation += (pt2[0] - pt[0]) * (pt2[1] + pt[1])
};
createdPolygon = false;
if (-0.000000001 < sum_orientation && sum_orientation <0.000000001){
coords[p][c][0][0] += 0.0000001;
coords[p][c][0][1] += 0.0000001;
coords[p][c][1][0] -= 0.0000001;
coords[p][c][1][1] -= 0.0000001;
coords[p][c][2][0] += 0.0000001;
coords[p][c][2][1] += 0.0000001;
if(polygon_pts.length==3) {
createdPolygon = true;
multipolygon_coords = coords[p][c];
polygon_part_loop = multipolygon_coords;
polygon_part = [polygon_part_loop];
polygon_all_parts.push(polygon_part);
}
else if (polygon_pts.length==4) {
createdPolygon = true;
multipolygon_coords = coords[p][c].slice(0,3);
polygon_part_loop = multipolygon_coords;
polygon_part = [polygon_part_loop];
polygon_all_parts.push(polygon_part);
/////////
multipolygon_coords = [coords[p][c][2], coords[p][c][3], coords[p][c][0]];
polygon_part_loop = multipolygon_coords;
polygon_part = [polygon_part_loop];
polygon_all_parts.push(polygon_part);
};
};
if (createdPolygon == false){ // if non-vertical, or vertical with more than 4 vertices
multipolygon_coords = coords[p][c];
polygon_part_loop = multipolygon_coords;
if (inner == false){
polygon_part = [polygon_part_loop];
polygon_all_parts.push(polygon_part);
}
else{
polygon_all_parts[polygon_all_parts.length-1].push(polygon_part_loop);
}
}
};
};
new_polygon = {"id": speckle_features.length, "type":"Feature",
"geometry": {"type": "MultiPolygon", "coordinates":polygon_all_parts},
"properties": speckle_data.features[i].properties,
"displayProperties": speckle_data.features[i].displayProperties };
new_polygon.displayProperties.lineWidth = 0.05
speckle_features.push(new_polygon);
}
else if (feature.displayProperties.object_type == "comment" || feature.geometry.type.includes("Point"))
{
//console.log(feature.properties)
try{
var labelText = feature.properties.text_html.replaceAll(' ', ' ').replaceAll('<br>', '\n').replace(/<[^>]+>/g, '');
}
catch{
var labelText = feature.properties.label;
}
coordinates = feature.geometry.coordinates
if (feature.geometry.type.includes("MultiPoint")){
coordinates = feature.geometry.coordinates[0]
}
coordinates = [coordinates[0], coordinates[1], 1.5]
speckle_features.push({"id": speckle_features.length, "type":"Feature",
"geometry": {"type": "Point", "coordinates": coordinates},
"properties": feature.properties,
"displayProperties":
{
"color": feature.displayProperties.color, //'rgba(10,132,255,255)',
"lineWidth": 2,
"radius": 10,
"object_type": "comments",
"label": labelText,
}
});
}
else
{
speckle_features.push({"id": speckle_features.length, "type":"Feature",
"geometry": {"type": feature.geometry.type, "coordinates":feature.geometry.coordinates},
"properties": feature.properties,
"displayProperties": feature.displayProperties });
}
}
speckle_data.features = speckle_features
//return speckle_features
}
function createSpeckleLayer(speckle_data, ind) {
// Create layer
speckle_layer = new deck.GeoJsonLayer({
id: `speckle_data_${ind}`,
data: speckle_data,
// Styles
filled: true,
opacity: 0.8,
getFillColor: f => rgbaToArgbList(f.displayProperties.color),
getLineWidth: f => f.displayProperties.lineWidth,
getLineColor: f => rgbaToArgbListDarker(f.displayProperties.color),
getPointRadius: f => f.displayProperties.radius / 2,
})
return speckle_layer;
}
async function delay( ms, state = null ) {
return new Promise( ( resolve, reject ) => {
window.setTimeout( () => resolve( state ), ms );
} );
}
function createTileLayer()
{
var tileLayer = new deck.TileLayer({
id: 'TileLayer',
data: 'https://basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}.png',
attribution: '© <a href="http://osm.org">OpenStreetMap</a> contributors, © <a href="https://carto.com/">CARTO</a>',
maxZoom: 19,
minZoom: 0,
renderSubLayers: props => {
const {boundingBox} = props.tile;
return new deck.BitmapLayer(props, {
data: null,
image: props.data,
bounds: [boundingBox[0][0], boundingBox[0][1], boundingBox[1][0], boundingBox[1][1]]
});
}
})
return tileLayer;
}
(async () => {
// functions using const: deckgl, layer_toggles
// and vars: all_data, all_layers, speckle_urls, extent
// or other local functions
function createDeck(){
var newDeckgl = new deck.DeckGL({
container: 'map',
initialViewState: initialViewState,
onViewStateChange: ({viewState}) => {
current_zoom = viewState.zoom;
if (all_layers.length>1 && viewAdjusted == false){
viewState.zoom = initialViewState.zoom
viewState.longitude = initialViewState.longitude
viewState.latitude = initialViewState.latitude
viewAdjusted = true
}
},
controller: true,
layers: all_layers
});
return newDeckgl;
}
function updateDeckLayers(newLayers){
deckgl.setProps({layers: newLayers});
}
function enableCheckboxesById(ind){
for (let i = 0; i < layer_toggles.length; i++) {
if (i==ind)
{
document.getElementById(layer_toggles[i]).disabled = false;
}
}
}
function getVisibleSpeckleLayers(all_layers){
// don't run if layers haven't loaded yet
if (all_data.length < speckle_urls.length){
return
}
var layersToShow = [all_layers[0]]
for (let i = 0; i < layer_toggles.length; i++){
var layer_checkbox = document.getElementById(layer_toggles[i])
if (layer_checkbox.checked == true){
if (all_data.length > i){ // create layers for datasets that are already loaded
layersToShow.push(createSpeckleLayer(all_data[i], i))
}
}
}
return layersToShow
}
async function toggleVisibilityByCheckboxes() {
layersToShow = getVisibleSpeckleLayers(all_layers) // speckle layers only
var layer_checkbox = document.getElementById("traffic_layer")
if (layer_checkbox.checked == true){
await addTrafficLayer(extent, layersToShow);
}
all_layers = layersToShow
updateDeckLayers(all_layers)
}
async function autoUpdateTrafficLayer(extent, all_layers) {
try {
while( true ) {
if (document.getElementById("traffic_layer").checked==true) {
enableCheckboxesById(2);
all_layers = getVisibleSpeckleLayers(all_layers);
await addTrafficLayer(extent, all_layers);
updateDeckLayers(all_layers);
}
await delay( 60000 );
}
}
catch( err ) {
console.error( err );
}
}
// define Speckle Models' URLs
var speckle_url1 = 'https://geo.speckle.systems/speckle/?speckleUrl=https://app.speckle.systems/projects/b973c777fe/models/12e10a7220&datatype=lines&preserveattributes=true';
var speckle_url2 = 'https://geo.speckle.systems/speckle/?speckleUrl=https://app.speckle.systems/projects/b973c777fe/models/49aff22443&limit=1000000&datatype=polygons&lon=26.7155164&lat=58.3739412&preserveattributes=true';
// set globally used variables for data layers and toggles
const speckle_urls = [speckle_url1, speckle_url2]
const layer_toggles = ["gis_layer", "rhino_layer", "traffic_layer"]
var all_layers = []
var all_data = []
// set globally used variables for the map view settings
var current_zoom = 18
var viewAdjusted = false
var extent = [-180,-90,180,90]
var initialViewState= {
longitude: extent[0] + (extent[2]-extent[0])/2,
latitude: extent[1] + (extent[3]-extent[1])/2,
zoom: 20,
maxZoom: 22,
minZoom: 12,
pitch: 60,
bearing: 1.469387755102039
}
// create event listeners for the UI checkboxes
for (let i = 0; i < layer_toggles.length; i++) {
document
.querySelector(`input[id=${layer_toggles[i]}]`)
.addEventListener('change', toggleVisibilityByCheckboxes);
}
// create first Tile Layer
var deckgl = null // placeholder, will be created after the first Speckle data is loaded
tile_layer = createTileLayer()
all_layers.push(tile_layer)
// start fetching Speckle data
for (let i = 0; i < speckle_urls.length; i++) {
const speckle_data = await fetch(speckle_urls[i], { headers: {'Accept': 'application/geo+json'}}).then(response => response.json());
// adjust view extent to the first loaded data, load deckGL
if (i == 0){
extent = speckle_data["extent"]
initialViewState.longitude = extent[0] + (extent[2]-extent[0])/2
initialViewState.latitude = extent[1] + (extent[3]-extent[1])/2
// Create deck.gl map
deckgl = createDeck();
}
fixVerticalPolygons(speckle_data)
all_data.push(speckle_data)
all_layers.push(createSpeckleLayer(speckle_data, i));
updateDeckLayers(all_layers)
enableCheckboxesById(i)
}
// turn on traffic layer creation and auto-update
autoUpdateTrafficLayer(extent, all_layers)
})();
</script>
</body>
</html>