-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
435 lines (416 loc) · 13.6 KB
/
main.js
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
// (c) This file is part of pgsql-omt-schema static demo website
// see https://github.com/feludwig/pgsql-omt-schema for details
// Author https://github.com/feludwig
//
// LICENSE https://github.com/feludwig/pgsql-omt-schema/blob/main/LICENSE
// GPL v3 in short :
// Permissions of this strong copyleft license are conditioned on making available
// complete source code of licensed works and modifications, which include larger
// works using a licensed work, under the same license.
// Copyright and license notices must be preserved.
function popup_text(f) {
var p=f.properties;
p['map_layer']=f.sourceLayer;
return Object.keys(p).map(k=>k+'='+p[k]).join('<br>');
}
function enable_cycle_routes() {
var layer_ids=[];
if (document.map.getSource('openmaptiles')==null) {
var chb=document.querySelector('#cyclecheckbox');
//chb.disabled=false;
chb.checked=false;
return;
}
fetch(document.cyclo_routes_json).then(r=>r.json()).then(function(c) {
// no new sources, but add a stub for the copyright attribution
document.map.addSource("cycle-routes-stub",c.sources[Object.keys(c.sources)[0]]);
c.layers.forEach(l=>{
if (l.id.includes('background') && document.map.getLayer('tunnel_service_track_casing')!=null) {
// add background layers UNDER tunnel_service_track_casing
document.map.addLayer(l,'tunnel_service_track_casing');
} else {
document.map.addLayer(l);
}
document.map.setLayoutProperty(l.id,'visibility','visible');
layer_ids.push(l.id);
});
});
//enable cyclecheckbox
var chb=document.querySelector('#cyclecheckbox');
chb.disabled=false;
chb.checked=true;
chb.onchange=function (e) {
console.log(e);
var setVis='none';
if (chb.checked) {
setVis='visible';
}
layer_ids.forEach(function(cl) {
document.map.setLayoutProperty(cl,'visibility',setVis);
});
};
}
function enable_contours() {
// append contours to current map
fetch(document.contours_json).then(r=>r.json()).then(function(c) {
Object.keys(c.sources).forEach(k=>{
document.map.addSource(k,c.sources[k]);
});
c.layers.forEach(l=>document.map.addLayer(l));
if (!document.show_contours_by_default) {
c.layers.forEach(l=>document.map.setLayoutProperty(l.id,'visibility','none'));
}
});
//enable contourscheckbox
var chb=document.querySelector('#contourscheckbox');
chb.disabled=false;
chb.checked=document.show_contours_by_default;
chb.onchange=function (e) {
console.log(e);
var setVis='none';
if (chb.checked) {
setVis='visible';
}
['contours10','contours50','contours100'].forEach(function(cl) {
document.map.setLayoutProperty(cl,'visibility',setVis);
});
};
}
function enable_tilebounds_checkbox() {
// enable tileboundscheckbox
var tbc=document.querySelector('#tileboundscheckbox');
tbc.disabled=false;
tbc.checked=false;
tbc.onchange=function (e) {
document.map.showTileBoundaries=tbc.checked;
};
}
function add_lhc_test() {
layer_name='lhc_test';
fetch(document.lhc_geojson).then(r=>r.json()).then(g=>{
console.log(g);
document.map.addSource(layer_name,{
type:'geojson',
data:g,
});
document.map.addLayer({
id: layer_name+'_line_layer',
type: 'line',
filter: [ '==', '$type', 'LineString' ],
source: layer_name,
paint: {
'line-color':'#ff00ff'
}
});
document.map.setLayoutProperty(layer_name+'_line_layer','visibility','visible');
});
}
function add_geojson_playground() {
document.querySelector('button#clear_playground').disabled=true;
// can be re-added without wiping data
// add geojson playground layer
if (document.playground_data==null) {
document.playground_data={
type:'FeatureCollection',
features:[]
};
}
document.map.addSource('playground',{
type:'geojson',
data:document.playground_data
});
document.map.addLayer({
id: 'playground_fill_layer',
type: 'fill',
filter: [ '==', '$type', 'Polygon' ],
source: 'playground',
paint: {
'fill-color':'#ff00ff',
'fill-antialias':true,
'fill-outline-color':'#ff00ff',
'fill-opacity':0.05
}
});
document.map.addLayer({
id: 'playground_line_layer',
type: 'line',
filter: [ '==', '$type', 'LineString' ],
source: 'playground',
paint: {
'line-color':'#ff00ff'
}
});
}
function get_centerpoint(g) {
console.log('center',g);
if (g.type=='Point') {
return g.coordinates;
} else if (g.type=='Polygon') {
// average of all points, WARN: weighed 1!
var res=[0,0];
var count=0;
g.coordinates[0].forEach(pt=>{
res[0]+=pt[0];
res[1]+=pt[1];
count+=1;
});
return [res[0]/count,res[1]/count];
} else if (g.type=='MultiPolygon') {
var maxlen=0;
var result_poly_coords;
g.coordinates.forEach(ar=>{
if (ar[0].length>maxlen) {
maxlen=ar[0].length;
result_poly_coords=ar[0];
}
});
return get_centerpoint({type:'Polygon',coordinates:[result_poly_coords]});
} else if (g.type=='MultiLineString') {
var maxlen=0;
var result_poly_coords;
g.coordinates.forEach(ar=>{
if (ar.length>maxlen) {
maxlen=ar.length;
result_poly_coords=ar;
}
});
return get_centerpoint({type:'LineString',coordinates:result_poly_coords});
} else if (g.type=='LineString') {
var avg_point=get_centerpoint({type:'Polygon',coordinates:[g.coordinates]});
var min_sq_dist=1e30;
var closest_point=g.coordinates[0];
g.coordinates.forEach(pt=>{
if (pt_sq_dist(pt,avg_point)<min_sq_dist) {
min_sq_dist=pt_sq_dist(pt,avg_point);
closest_point=pt;
}
});
return closest_point;
}
}
function pt_sq_dist(a,b) {
return (a[0]-b[0])*(a[0]-b[0])+(a[1]-b[1])*(a[1]-b[1]);
}
function replace_recursive_prop(subject,source,target) {
// any-type subject style property: replace source with target.
// for object and list types, descend recursively while keeping
// everything else the same
if (JSON.stringify(subject)==JSON.stringify(source)) {
return target;
} else if (typeof(subject)=='number'||typeof(subject)=='boolean') {
return subject;
} else if (typeof(subject)=='string' && typeof(target)=='string') {
return subject.replaceAll(source,target);
} else if (Array.isArray(subject)) {
return subject.map((i)=>replace_recursive_prop(i,source,target));
} else if (typeof(subject)=='object') {
Object.keys(subject).forEach(k=>{
subject[k]=replace_recursive_prop(subject[k],source,target);
});
return subject;
//} else {
} else if (typeof(subject)=='string' && typeof(target)!='string' && typeof(source)=='string') {
// example subject='dc.sr.tsr.t', source='.' and target=['get','name']
var as_list=subject.split(source);
// -> ['dc','sr','tsr','t']
if (as_list.length==1) {
return subject; // nothin in there to replace
}
return as_list.reduce((accu,item,ix)=>{
if (ix==0) {
// no target in here
if (item=='') {
return [...accu];
}
return [...accu,item];
} else {
if (item=='') {
return [...accu,target];
}
return [...accu,target,item];
}
},['concat']);
// -> ['concat','dc',['get','name'],'sr',['get','name'],'tsr',['get','name'],'t']
}
return subject;
}
function set_name_property(lang) {
if (lang==null) {
// go through style and change every occurence of "name:latin" to "name"
var new_name=['get','name'];
} else if (lang=='local') {
var new_name=['get','name'];
} else {
var new_name=['case',['has','name_'+lang],['get','name_'+lang],['get','name']];
}
document.map.getStyle().layers.forEach(l=>{
if (l.layout!=null && l.layout['text-field']!=null) {
//console.log(l.id,'orig=',JSON.stringify(l.layout['text-field']));
var in_prop=document.map.getLayoutProperty(l.id,'text-field');
if (lang==null) {
//console.log(l.id,in_prop,JSON.stringify(in_prop));
// cannonicalize
var new_prop3=replace_recursive_prop(in_prop,'{name:nonlatin}',['get','name:nonlatin']);
var new_prop2=replace_recursive_prop(new_prop3,['get','name:latin'],new_name);
var new_prop=replace_recursive_prop(new_prop2,'{name:latin}',new_name);
//console.log(l.id,new_prop,JSON.stringify(new_prop));
} else if (lang=='local') {
var new_prop=replace_recursive_prop(in_prop,document.current_name,new_name);
} else {
var new_prop=replace_recursive_prop(in_prop,document.current_name,new_name);
}
document.map.setLayoutProperty(l.id,'text-field',new_prop);
}
});
document.current_name=new_name;
}
function add_click_listener() {
var map_layers_ordering=['poi','mountain_peak','park','place','boundary',
'aerodrome_label','aeroway','housenumber','building','water_name','water',
'transportation_name','transportation','waterway','landuse','landcover'];
document.map.on('click',(e)=> {
console.log('clicked');
var feature_ix=map_layers_ordering.length;
var selected_feature=null;
document.map.queryRenderedFeatures(e.point).forEach((f)=>{
var curr_ix=map_layers_ordering.indexOf(f.sourceLayer);
if (f.source=='playground') {
return;
}
// accept/ignore all clicks on class='residential's
if (curr_ix<feature_ix && (true || ! ['residential'].includes(f.properties.class))) {
feature_ix=curr_ix;
selected_feature=f;
}
});
if (selected_feature==null) {
return;
}
var f=selected_feature;
document.playground_data.features.push(f);
var pp=new maplibregl.Popup();
pp.setLngLat(get_centerpoint(f.geometry)).setHTML(popup_text(f)).addTo(document.map);
if (typeof lookup_add_text !='undefined') {
lookup_add_text(f,pp);
}
document.map.getSource('playground').setData(document.playground_data);
if (f.geometry.type!='Point') {
document.querySelector('button#clear_playground').disabled=false;
}
});
}
function clear_playground() {
document.playground_data.features=[];
document.map.getSource('playground').setData(document.playground_data);
document.querySelector('button#clear_playground').disabled=true;
}
function add_relief() {
document.querySelector('button#add_relief').disabled=true;
document.map.addSource('terrarium',{
"type": "raster-dem",
"tiles": [
"https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png"
],
"minzoom": 0,
"maxzoom": 15,
"tileSize": 256,
"encoding": "terrarium"
});
if (false) { // too much
document.map.addLayer({
"id": "terrain-rgb-hillshade",
"source": "terrarium",
"type": "hillshade",
"paint": {
"hillshade-shadow-color": "hsl(39, 21%, 33%)",
"hillshade-illumination-direction": 315,
"hillshade-exaggeration": 0.8
}
});
}
document.map.setTerrain({source:"terrarium",exaggeration:3});
}
function enable_style_selector() {
var st=document.querySelector('#styleselector');
document.styles.forEach((s,s_ix)=> {
var op=document.createElement('option');
op.name=s_ix;
op.innerHTML=s.name;
op.value=s.href;
st.appendChild(op);
});
st.onchange=(ev)=>{
switch_style_over(st.selectedIndex);
};
}
function switch_style_over(tgt_index) {
document.querySelector('select[id=styleselector]').disabled=true;
document.map.setStyle(document.styles[tgt_index].href);
document.map.once('styledata',()=>{
if (document.map.getSource('contours')==null) {
enable_contours();
}
enable_cycle_routes();
if (document.map.getSource('playground')==null) {
add_geojson_playground();
}
});
document.map.once('render',(e)=>{
set_name_property(); // cannonicalize name:latin -> name
set_name_property(document.current_name);
document.map.once('render',(e)=>{
document.querySelector('select[id=styleselector]').disabled=false;
});
});
}
function add_name_controls() {
var all_name_selectors=document.querySelectorAll('input[id^=rad_]');
document.querySelector('input[id=rad_local]').checked=true;
all_name_selectors.forEach((e)=>{
e.onchange=(ev)=>{
all_name_selectors.forEach((r)=>{r.disabled=true});
set_name_property(ev.target.value);
all_name_selectors.forEach((r)=>{r.disabled=false});
};
});
}
function main() {
document.querySelectorAll('input,button,select').forEach((r)=>{r.disabled=true});
try {
document.map = new maplibregl.Map({
container: 'map',
style: document.styles[0].href, // stylesheet location
// limattal, zurich, switzerland
center: [8.4628, 47.3918],
zoom: 11.6,
// show # in url, when copying the url the lat,lon,zoom,tilt,rotation position is included
hash: true,
});
} catch (err) {
try {
var displ_msg=JSON.parse(err.message).message.toString();
} catch (err2) {
var displ_msg=err.toString();
}
document.querySelector('p#loading').innerHTML=displ_msg;
alert(displ_msg);
}
document.map.addControl(new maplibregl.ScaleControl({ maxWidth: 250, unit: 'metric' }));
document.map.once('load',function() {
set_name_property();
add_name_controls();
document.querySelector('p#loading').remove();
enable_contours();
enable_cycle_routes();
enable_tilebounds_checkbox();
enable_style_selector();
//add_relief();
add_geojson_playground();
// depends on geojson playground
add_click_listener();
});
document.map.once('render',(e)=>{
document.querySelectorAll('input,button,select').forEach((r)=>{r.disabled=false});
});
}
main();