Passed
Pull Request — master (#24)
by Mark
07:53
created

script.js (28 issues)

1
/*
2
 * Copyright (c) 2008-2022 Mark C. Prins <[email protected]>
3
 *
4
 * Permission to use, copy, modify, and distribute this software for any
5
 * purpose with or without fee is hereby granted, provided that the above
6
 * copyright notice and this permission notice appear in all copies.
7
 *
8
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15
 */
16
17
18
/**
19
 * Test for css support in the browser by sniffing for a css class we added
20
 * using javascript added by the action plugin; this is an edge case because
21
 * browsers that support javascript generally support css as well.
22
 *
23
 * @returns {Boolean} true when the browser supports css (and implicitly
24
 *          javascript)
25
 */
26
function olTestCSSsupport() {
27
    return (jQuery('.olCSSsupported').length > 0);
28
}
29
30
/**
31
 * Creates a DocumentFragment to insert into the dom.
32
 *
33
 * @param mapid
34
 *            id for the map div
35
 * @param width
36
 *            width for the map div
37
 * @param height
38
 *            height for the map div
39
 * @returns a {DocumentFragment} element that can be injected into the dom
40
 */
41
function olCreateMaptag(mapid, width, height) {
42
    const // fragment
43
        frag = document.createDocumentFragment(),
44
        // temp node
45
        temp = document.createElement('div');
46
    temp.innerHTML = '<div id="' + mapid + '-olContainer" class="olContainer olWebOnly">'
47
        // map
48
        + '<div id="' + mapid + '" tabindex="0" style="width:' + width + ';height:' + height + ';" class="olMap"></div>'
49
        + '</div>';
50
    while (temp.firstChild) {
51
        frag.appendChild(temp.firstChild);
52
    }
53
    return frag;
54
}
55
56
/**
57
 * Create the map based on the params given.
58
 *
59
 * @param mapOpts {Object}
60
 *            mapOpts MapOptions hash {id:'olmap', width:500px, height:500px,
61
 *            lat:6710200, lon:506500, zoom:13, controls:1,
62
 *            baselyr:'', kmlfile:'', gpxfile:'', geojsonfile,
63
 *            summary:''}
64
 * @param poi {Array}
65
 *            OLmapPOI array with POI's [ {lat:6710300,lon:506000,txt:'instap
66
 *            punt',angle:180,opacity:.9,img:'', rowId:n},... ]);
67
 *
68
 * @return {ol.Map} the created map
69
 */
70
function createMap(mapOpts, poi) {
71
72
    // const mapOpts = olMapData[0].mapOpts;
73
    // const poi = olMapData[0].poi;
74
75
    if (!olEnable) {
0 ignored issues
show
If you intend to check if the variable olEnable is declared in the current environment, consider using typeof olEnable === "undefined" instead. This is safe if the variable is not actually declared.
Loading history...
76
        return null;
77
    }
78
    if (!olTestCSSsupport()) {
79
        olEnable = false;
0 ignored issues
show
The variable olEnable seems to be never declared. Assigning variables without defining them first makes them global. If this was intended, consider making it explicit like using window.olEnable.
Loading history...
80
        return null;
81
    }
82
83
    // find map element location
84
    const cleartag = document.getElementById(mapOpts.id + '-clearer');
85
    if (cleartag === null) {
86
        return null;
87
    }
88
    // create map element and add to document
89
    const fragment = olCreateMaptag(mapOpts.id, mapOpts.width, mapOpts.height);
90
    cleartag.parentNode.insertBefore(fragment, cleartag);
91
92
    /** dynamic map extent. */
93
    let extent = ol.extent.createEmpty();
0 ignored issues
show
The variable ol seems to be never declared. If this is a global, consider adding a /** global: ol */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
94
    let overlayGroup = new ol.layer.Group({title: 'Overlays', fold: 'open', layers: []});
95
    const baseLyrGroup = new ol.layer.Group({'title': 'Base maps', layers: []});
96
97
    const map = new ol.Map({
98
        target:   document.getElementById(mapOpts.id),
99
        layers:   [baseLyrGroup, overlayGroup],
100
        view:     new ol.View({
101
            center:     ol.proj.transform([mapOpts.lon, mapOpts.lat], 'EPSG:4326', 'EPSG:3857'),
102
            zoom:       mapOpts.zoom,
103
            projection: 'EPSG:3857'
104
        }),
105
        controls: [
106
            new ol.control.Attribution({
107
                collapsible: true,
108
                collapsed:   true
109
            })
110
        ]
111
    });
112
113
    if (osmEnable) {
0 ignored issues
show
If you intend to check if the variable osmEnable is declared in the current environment, consider using typeof osmEnable === "undefined" instead. This is safe if the variable is not actually declared.
Loading history...
114
        baseLyrGroup.getLayers().push(
115
            new ol.layer.Tile({
116
                visible: true,
117
                title:   'OSM',
118
                type:    'base',
119
                source:  new ol.source.OSM()
120
            }));
121
122
        baseLyrGroup.getLayers().push(
123
            new ol.layer.Tile({
124
                visible: mapOpts.baselyr === "cycle map",
125
                title:   'cycle map',
126
                type:    'base',
127
                source:  new ol.source.OSM({
128
                    url:          'https://{a-c}.tile.thunderforest.com/cycle/{z}/{x}/{y}.png?apikey=' + tfApiKey,
0 ignored issues
show
The variable tfApiKey seems to be never declared. If this is a global, consider adding a /** global: tfApiKey */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
129
                    attributions: 'Data &copy;ODbL <a href="https://openstreetmap.org/copyright" target="_blank">OpenStreetMap</a>, '
130
                                      + 'Tiles &copy;<a href="https://www.thunderforest.com/" target="_blank">Thunderforest</a>'
131
                                      + '<img src="https://www.thunderforest.com/favicon.ico" alt="Thunderforest logo"/>'
132
                })
133
            }));
134
135
        baseLyrGroup.getLayers().push(
136
            new ol.layer.Tile({
137
                visible: mapOpts.baselyr === "transport",
138
                title:   'transport',
139
                type:    'base',
140
                source:  new ol.source.OSM({
141
                    url:          'https://{a-c}.tile.thunderforest.com/transport/{z}/{x}/{y}.png?apikey=' + tfApiKey,
142
                    attributions: 'Data &copy;ODbL <a href="https://openstreetmap.org/copyright" target="_blank">OpenStreetMap</a>, '
143
                                      + 'Tiles &copy;<a href="https://www.thunderforest.com/" target="_blank">Thunderforest</a>'
144
                                      + '<img src="https://www.thunderforest.com/favicon.ico" alt="Thunderforest logo"/>'
145
                })
146
            }));
147
148
        baseLyrGroup.getLayers().push(
149
            new ol.layer.Tile({
150
                visible: mapOpts.baselyr === "landscape",
151
                title:   'landscape',
152
                type:    'base',
153
                source:  new ol.source.OSM({
154
                    url:          'https://{a-c}.tile.thunderforest.com/landscape/{z}/{x}/{y}.png?apikey=' + tfApiKey,
155
                    attributions: 'Data &copy;ODbL <a href="https://openstreetmap.org/copyright" target="_blank">OpenStreetMap</a>, '
156
                                      + 'Tiles &copy;<a href="https://www.thunderforest.com/" target="_blank">Thunderforest</a>'
157
                                      + '<img src="https://www.thunderforest.com/favicon.ico" alt="Thunderforest logo"/>'
158
                })
159
            }));
160
161
        baseLyrGroup.getLayers().push(
162
            new ol.layer.Tile({
163
                visible: mapOpts.baselyr === "outdoors",
164
                title:   'outdoors',
165
                type:    'base',
166
                source:  new ol.source.OSM({
167
                    url:          'https://{a-c}.tile.thunderforest.com/outdoors/{z}/{x}/{y}.png?apikey=' + tfApiKey,
168
                    attributions: 'Data &copy;ODbL <a href="https://openstreetmap.org/copyright" target="_blank">OpenStreetMap</a>, '
169
                                      + 'Tiles &copy;<a href="https://www.thunderforest.com/" target="_blank">Thunderforest</a>'
170
                                      + '<img src="https://www.thunderforest.com/favicon.ico" alt="Thunderforest logo"/>'
171
                })
172
            }));
173
    }
174
175
    if (bEnable && bApiKey !== '') {
0 ignored issues
show
If you intend to check if the variable bEnable is declared in the current environment, consider using typeof bEnable === "undefined" instead. This is safe if the variable is not actually declared.
Loading history...
The variable bApiKey seems to be never declared. If this is a global, consider adding a /** global: bApiKey */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
176
        baseLyrGroup.getLayers().push(
177
            new ol.layer.Tile({
178
                visible: mapOpts.baselyr === "bing road",
179
                title:   'bing road',
180
                type:    'base',
181
                source:  new ol.source.BingMaps({
182
                    key:        bApiKey,
183
                    imagerySet: 'Road'
184
                })
185
            }));
186
187
        baseLyrGroup.getLayers().push(
188
            new ol.layer.Tile({
189
                visible: mapOpts.baselyr === "bing sat",
190
                title:   'bing sat',
191
                type:    'base',
192
                source:  new ol.source.BingMaps({
193
                    key:        bApiKey,
194
                    imagerySet: 'Aerial'
195
                })
196
            }));
197
198
        baseLyrGroup.getLayers().push(
199
            new ol.layer.Tile({
200
                visible: mapOpts.baselyr === "bing hybrid",
201
                title:   'bing hybrid',
202
                type:    'base',
203
                source:  new ol.source.BingMaps({
204
                    key:        bApiKey,
205
                    imagerySet: 'AerialWithLabels'
206
                })
207
            }));
208
    }
209
210
    if (stamenEnable) {
0 ignored issues
show
If you intend to check if the variable stamenEnable is declared in the current environment, consider using typeof stamenEnable === "undefined" instead. This is safe if the variable is not actually declared.
Loading history...
211
        baseLyrGroup.getLayers().push(
212
            new ol.layer.Tile({
213
                visible: mapOpts.baselyr === "toner",
214
                type:    'base',
215
                title:   'toner',
216
                source:  new ol.source.Stamen({layer: 'toner'})
217
            })
218
        );
219
220
        baseLyrGroup.getLayers().push(
221
            new ol.layer.Tile({
222
                visible: mapOpts.baselyr === "terrain",
223
                type:    'base',
224
                title:   'terrain',
225
                source:  new ol.source.Stamen({layer: 'terrain'})
226
            })
227
        );
228
    }
229
230
    extent = ol.extent.extend(extent, map.getView().calculateExtent());
231
232
    const iconScale = 1.0;
233
    const vectorSource = new ol.source.Vector();
234
    poi.forEach((p) => {
235
        const f = new ol.Feature({
0 ignored issues
show
The variable ol seems to be never declared. If this is a global, consider adding a /** global: ol */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
236
            geometry:    new ol.geom.Point(ol.proj.fromLonLat([p.lon, p.lat])),
237
            description: p.txt,
238
            img:         p.img,
239
            rowId:       p.rowId,
240
            lat:         p.lat,
241
            lon:         p.lon,
242
            angle:       p.angle,
243
            alt:         p.img.substring(0, p.img.lastIndexOf("."))
244
        });
245
        f.setId(p.rowId);
246
        f.setStyle(new ol.style.Style({
247
            text:      new ol.style.Text({
248
                text:           "" + p.rowId,
249
                textAlign:      'center',
250
                textBaseline:   'middle',
251
                offsetX:        (8 + 4) * iconScale,
252
                offsetY:        -8 * iconScale,
253
                scale:          iconScale,
254
                fill:           new ol.style.Fill({color: 'rgb(0,0,0)'}),
255
                font:           'bold 1em monospace',
256
                backgroundFill: new ol.style.Fill({color: 'rgba(255,255,255,.4)'})
257
            }), image: new ol.style.Icon({
258
                src:         DOKU_BASE + "lib/plugins/openlayersmap/icons/" + p.img,
0 ignored issues
show
The variable DOKU_BASE seems to be never declared. If this is a global, consider adding a /** global: DOKU_BASE */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
259
                crossOrigin: '',
260
                opacity:     p.opacity,
261
                scale:       iconScale,
262
                rotation:    p.angle * Math.PI / 180,
263
            }),
264
        }));
265
        vectorSource.addFeature(f);
266
    });
267
268
    const vectorLayer = new ol.layer.Vector({title: 'POI', visible: true, source: vectorSource});
269
    overlayGroup.getLayers().push(vectorLayer);
270
    if (mapOpts.autozoom) {
271
        extent = ol.extent.extend(extent, vectorSource.getExtent());
272
        map.getView().fit(extent);
273
    }
274
275
    if (mapOpts.controls === 1) {
276
        map.addControl(new ol.control.Zoom());
277
        map.addControl(new ol.control.ScaleLine({bar: true, text: true}));
278
        map.addControl(new ol.control.MousePosition({
279
            coordinateFormat: ol.coordinate.createStringXY(4), projection: 'EPSG:4326',
280
        }));
281
        map.addControl(new ol.control.FullScreen({
282
            label: '✈'
283
        }));
284
        map.addControl(new ol.control.OverviewMap({
285
            label:  '+',
286
            layers: [new ol.layer.Tile({
287
                source: new ol.source.OSM()
288
            })]
289
        }));
290
        map.addControl(new ol.control.LayerSwitcher({
291
            activationMode: 'click',
292
            label:          '\u2630',
293
            collapseLabel:  '\u00BB',
294
        }));
295
    }
296
297
    if (mapOpts.kmlfile.length > 0) {
298
        try {
299
            const kmlSource = new ol.source.Vector({
300
                url:    DOKU_BASE + "lib/exe/fetch.php?media=" + mapOpts.kmlfile,
0 ignored issues
show
The variable DOKU_BASE seems to be never declared. If this is a global, consider adding a /** global: DOKU_BASE */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
301
                format: new ol.format.KML(),
302
            });
303
            overlayGroup.getLayers().push(new ol.layer.Vector({title: 'KML file', visible: true, source: kmlSource}));
304
305
            if (mapOpts.autozoom) {
306
                kmlSource.once('change', function () {
307
                    extent = ol.extent.extend(extent, kmlSource.getExtent());
0 ignored issues
show
The variable ol seems to be never declared. If this is a global, consider adding a /** global: ol */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
308
                    map.getView().fit(extent);
309
                });
310
            }
311
        } catch (e) {
312
            console.error(e);
313
        }
314
    }
315
316
    if (mapOpts.geojsonfile.length > 0) {
317
        try {
318
            // these are the same colour as in StaticMap#drawJSON()
319
            const geoJsonStyle = {
320
                'Point':           new ol.style.Style({
321
                    image: new ol.style.Circle({
322
                        fill:   new ol.style.Fill({
323
                            color: 'rgba(255,0,255,0.4)',
324
                        }),
325
                        radius: 5,
326
                        stroke: new ol.style.Stroke({
327
                            color: 'rgba(255,0,255,0.9)',
328
                            width: 1,
329
                        }),
330
                    }),
331
                }),
332
                'LineString':      new ol.style.Style({
333
                    stroke: new ol.style.Stroke({
334
                        color: 'rgba(255,0,255,0.9)',
335
                        width: 3,
336
                    }),
337
                }),
338
                'MultiLineString': new ol.style.Style({
339
                    stroke: new ol.style.Stroke({
340
                        color: 'rgba(255,0,255,0.9)',
341
                        width: 3,
342
                    }),
343
                }),
344
                'Polygon':         new ol.style.Style({
345
                    stroke: new ol.style.Stroke({
346
                        color: 'rgba(255,0,255,0.9)',
347
                        width: 3,
348
                    }),
349
                    fill:   new ol.style.Fill({
350
                        color: 'rgba(255,0,255,0.4)',
351
                    }),
352
                }),
353
                'MultiPolygon':    new ol.style.Style({
354
                    stroke: new ol.style.Stroke({
355
                        color: 'rgba(255,0,255,0.9)',
356
                        width: 3,
357
                    }),
358
                    fill:   new ol.style.Fill({
359
                        color: 'rgba(255,0,255,0.4)',
360
                    }),
361
                }),
362
            };
363
            const geoJsonSource = new ol.source.Vector({
364
                url:    DOKU_BASE + "lib/exe/fetch.php?media=" + mapOpts.geojsonfile,
365
                format: new ol.format.GeoJSON(),
366
            });
367
            overlayGroup.getLayers().push(new ol.layer.Vector({
368
                title: 'GeoJSON file', visible: true, source: geoJsonSource,
369
                style: function (feature) {
370
                    return geoJsonStyle[feature.getGeometry().getType()];
371
                },
372
            }));
373
374
            if (mapOpts.autozoom) {
375
                geoJsonSource.once('change', function () {
376
                    extent = ol.extent.extend(extent, geoJsonSource.getExtent());
0 ignored issues
show
The variable ol seems to be never declared. If this is a global, consider adding a /** global: ol */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
377
                    map.getView().fit(extent);
378
                });
379
            }
380
        } catch (e) {
381
            console.error(e);
382
        }
383
    }
384
385
    if (mapOpts.gpxfile.length > 0) {
386
        try {
387
            // these are the same colour as in StaticMap#drawGPX()
388
            const gpxJsonStyle = {
389
                'Point':           new ol.style.Style({
390
                    image: new ol.style.Circle({
391
                        fill:   new ol.style.Fill({
392
                            color: 'rgba(0,0,255,0.4)',
393
                        }),
394
                        radius: 5,
395
                        stroke: new ol.style.Stroke({
396
                            color: 'rgba(0,0,255,0.9)',
397
                            width: 1,
398
                        }),
399
                    }),
400
                }),
401
                'LineString':      new ol.style.Style({
402
                    stroke: new ol.style.Stroke({
403
                        color: 'rgba(0,0,255,0.9)',
404
                        width: 3,
405
                    }),
406
                }),
407
                'MultiLineString': new ol.style.Style({
408
                    stroke: new ol.style.Stroke({
409
                        color: 'rgba(0,0,255,0.9)',
410
                        width: 3,
411
                    }),
412
                }),
413
            };
414
            const gpxSource = new ol.source.Vector({
415
                url:    DOKU_BASE + "lib/exe/fetch.php?media=" + mapOpts.gpxfile,
416
                format: new ol.format.GPX(),
417
            });
418
            overlayGroup.getLayers().push(new ol.layer.Vector({
419
                title: 'GPS track', visible: true, source: gpxSource,
420
                style: function (feature) {
421
                    return gpxJsonStyle[feature.getGeometry().getType()];
422
                },
423
            }));
424
425
            if (mapOpts.autozoom) {
426
                gpxSource.once('change', function () {
427
                    extent = ol.extent.extend(extent, gpxSource.getExtent());
0 ignored issues
show
The variable ol seems to be never declared. If this is a global, consider adding a /** global: ol */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
428
                    map.getView().fit(extent);
429
                });
430
            }
431
        } catch (e) {
432
            console.error(e);
433
        }
434
    }
435
436
    const container = document.getElementById('popup');
437
    const content = document.getElementById('popup-content');
438
    const closer = document.getElementById('popup-closer');
439
440
    const overlay = new ol.Overlay({
441
        element:     container,
442
        positioning: 'center-center',
443
        stopEvent:   true,
444
        autoPan:     {
445
            animation: {
446
                duration: 250,
447
            }
448
        },
449
    });
450
    map.addOverlay(overlay);
451
452
    /**
453
     * Add a click handler to hide the popup.
454
     * @return {boolean} Don't follow the href.
455
     */
456
    closer.onclick = function () {
457
        overlay.setPosition(undefined);
458
        closer.blur();
459
        return false;
460
    };
461
462
    // display popup on click
463
    map.on('singleclick', function (evt) {
464
        const selFeature = map.forEachFeatureAtPixel(evt.pixel, function (feature) {
465
            return feature;
466
        });
467
        if (selFeature) {
468
            overlay.setPosition(evt.coordinate);
469
470
            let pContent = '<div class="spacer">&nbsp;</div>';
471
            // let locDesc = '';
472
473
            if (selFeature.get('rowId') !== undefined) {
474
                pContent += '<span class="rowId">' + selFeature.get('rowId') + ': </span>';
475
            }
476
            if (selFeature.get('name') !== undefined) {
477
                pContent += '<span class="txt">' + selFeature.get('name') + '</span>';
478
                // locDesc = selFeature.get('name');
479
                // TODO strip <p> tag from locDesc
480
                // locDesc = selFeature.get('name').split(/\s+/).slice(0,2).join('+');
481
            }
482
            if (selFeature.get('ele') !== undefined) {
483
                pContent += '<div class="ele">elevation: ' + selFeature.get('ele') + '</div>';
484
            }
485
            if (selFeature.get('type') !== undefined) {
486
                pContent += '<div>' + selFeature.get('type') + '</div>';
487
            }
488
            if (selFeature.get('time') !== undefined) {
489
                pContent += '<div class="time">time: ' + selFeature.get('time') + '</div>';
490
            }
491
            if (selFeature.get('description') !== undefined) {
492
                pContent += '<div class="desc">' + selFeature.get('description') + '</div>';
493
            }
494
            if (selFeature.get('img') !== undefined) {
495
                const _alt = selFeature.get('alt');
496
                pContent += '<div class="coord" title="lat;lon">' +
497
                    '<img alt="' + _alt + '" src="' + DOKU_BASE + 'lib/plugins/openlayersmap/icons/' + selFeature.get('img') +
0 ignored issues
show
The variable DOKU_BASE seems to be never declared. If this is a global, consider adding a /** global: DOKU_BASE */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
498
                    '" width="16" height="16" ' + 'style="transform:rotate(' + selFeature.get('angle') + 'deg)" />&nbsp;' +
499
                    '<a href="geo:' + selFeature.get('lat') + ',' + selFeature.get('lon') + '?q=' + selFeature.get('lat') +
500
                    ',' + selFeature.get('lon') + '(' + selFeature.get('alt') + ')" title="Open in navigation app">' +
501
                    ol.coordinate.format([selFeature.get('lon'), selFeature.get('lat')], '{x}º; {y}º', 4) + '</a></div>';
0 ignored issues
show
The variable ol seems to be never declared. If this is a global, consider adding a /** global: ol */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
502
            }
503
            content.innerHTML = pContent;
504
        } else {
0 ignored issues
show
Comprehensibility Documentation Best Practice introduced by
This code block is empty. Consider removing it or adding a comment to explain.
Loading history...
505
            // do nothing...
506
        }
507
    });
508
509
    // change mouse cursor when over marker
510
    map.on('pointermove', function (e) {
511
        const pixel = map.getEventPixel(e.originalEvent);
512
        const hit = map.hasFeatureAtPixel(pixel);
513
        map.getTarget().style.cursor = hit ? 'pointer' : '';
514
    });
515
516
    return map;
517
}
518
519
/**
520
 * add layers to the map based on the olMapOverlays object.
521
 */
522
function olovAddToMap() {
523
    for (const key in olMapOverlays) {
0 ignored issues
show
The variable olMapOverlays seems to be never declared. If this is a global, consider adding a /** global: olMapOverlays */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
524
        const overlay = olMapOverlays[key];
525
        const m = olMaps[overlay.id];
0 ignored issues
show
The variable olMaps seems to be never declared. If this is a global, consider adding a /** global: olMaps */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
526
527
        switch (overlay.type) {
528
            case 'osm':
529
                m.addLayer(new ol.layer.Tile({
0 ignored issues
show
The variable ol seems to be never declared. If this is a global, consider adding a /** global: ol */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
530
                    title:   overlay.name,
531
                    visible: (overlay.visible).toLowerCase() === 'true',
532
                    opacity: parseFloat(overlay.opacity),
533
                    source:  new ol.source.OSM({
534
                        url:          overlay.url,
535
                        crossOrigin:  'Anonymous',
536
                        attributions: overlay.attribution
537
                    })
538
                }));
539
                break;
540
            case 'wms':
541
                m.addLayer(new ol.layer.Image({
542
                    title:   overlay.name,
543
                    opacity: parseFloat(overlay.opacity),
544
                    visible: (overlay.visible).toLowerCase() === 'true',
545
                    source:  new ol.source.ImageWMS({
546
                        url:          overlay.url,
547
                        params:       {
548
                            'LAYERS':      overlay.layers,
549
                            'VERSION':     overlay.version,
550
                            'TRANSPARENT': overlay.transparent,
551
                            'FORMAT':      overlay.format
552
                        },
553
                        ratio:        1,
554
                        crossOrigin:  'Anonymous',
555
                        attributions: overlay.attribution
556
                    })
557
                }));
558
                break;
559
            case 'ags':
560
                m.addLayer(new ol.layer.Image({
561
                    title:   overlay.name,
562
                    opacity: parseFloat(overlay.opacity),
563
                    visible: (overlay.visible).toLowerCase() === 'true',
564
                    source:  new ol.source.ImageArcGISRest({
565
                        url:          overlay.url,
566
                        params:       {
567
                            'LAYERS':      overlay.layers,
568
                            'TRANSPARENT': overlay.transparent,
569
                            'FORMAT':      overlay.format
570
                        },
571
                        ratio:        1,
572
                        crossOrigin:  'Anonymous',
573
                        attributions: overlay.attribution
574
                    })
575
                }));
576
                break;
577
            // case 'mapillary':
578
            //     var mUrl = 'http://api.mapillary.com/v1/im/search?';
579
            //     if (overlay.skey !== '') {
580
            //         mUrl = 'http://api.mapillary.com/v1/im/sequence?';
581
            //     }
582
            //     var mLyr = new OpenLayers.Layer.Vector(
583
            //         "Mapillary", {
584
            //             projection:  new OpenLayers.Projection("EPSG:4326"),
585
            //             strategies:  [new OpenLayers.Strategy.BBOX({
586
            //                 ratio:     1.1,
587
            //                 resFactor: 1.5
588
            //             }) /* ,new OpenLayers.Strategy.Cluster({}) */],
589
            //             protocol:    new OpenLayers.Protocol.HTTP({
590
            //                 url:            mUrl,
591
            //                 format:         new OpenLayers.Format.GeoJSON(),
592
            //                 params:         {
593
            //                     // default to max. 250 locations
594
            //                     'max-results': 250,
595
            //                     'geojson':     true,
596
            //                     'skey':        overlay.skey
597
            //                 },
598
            //                 filterToParams: function (filter, params) {
599
            //                     if (filter.type === OpenLayers.Filter.Spatial.BBOX) {
600
            //                         // override the bbox serialization of
601
            //                         // the filter to give the Mapillary
602
            //                         // specific bounds
603
            //                         params['min-lat'] = filter.value.bottom;
604
            //                         params['max-lat'] = filter.value.top;
605
            //                         params['min-lon'] = filter.value.left;
606
            //                         params['max-lon'] = filter.value.right;
607
            //                         // if the width of our bbox width is
608
            //                         // less than 0.15 degrees drop the max
609
            //                         // results
610
            //                         if (filter.value.top - filter.value.bottom < .15) {
611
            //                             OpenLayers.Console.debug('dropping max-results parameter, width is: ',
612
            //                                 filter.value.top - filter.value.bottom);
613
            //                             params['max-results'] = null;
614
            //                         }
615
            //                     }
616
            //                     return params;
617
            //                 }
618
            //             }),
619
            //             styleMap:    new OpenLayers.StyleMap({
620
            //                 'default': {
621
            //                     cursor:          'help',
622
            //                     rotation:        '${ca}',
623
            //                     externalGraphic: DOKU_BASE + 'lib/plugins/openlayersmapoverlays/icons/arrow-up-20.png',
624
            //                     graphicHeight:   20,
625
            //                     graphicWidth:    20,
626
            //                 },
627
            //                 'select':  {
628
            //                     externalGraphic: DOKU_BASE + 'lib/plugins/openlayersmapoverlays/icons/arrow-up-20-select.png',
629
            //                     label:           '${location}',
630
            //                     fontSize:        '1em',
631
            //                     fontFamily:      'monospace',
632
            //                     labelXOffset:    '0.5',
633
            //                     labelYOffset:    '0.5',
634
            //                     labelAlign:      'lb',
635
            //                 }
636
            //             }),
637
            //             attribution: '<a href="http://www.mapillary.com/legal.html">' +
638
            //                              '<img src="http://mapillary.com/favicon.ico" ' +
639
            //                              'alt="Mapillary" height="16" width="16" />Mapillary (CC-BY-SA)',
640
            //             visibility:  (overlay.visible).toLowerCase() == 'true',
641
            //         });
642
            //     m.addLayer(mLyr);
643
            //     selectControl.addLayer(mLyr);
644
            //     break;
645
            // case 'search':
646
            //     m.addLayer(new OpenLayers.Layer.Vector(
647
            //         overlay.name,
648
            //         overlay.url,
649
            //         {
650
            //             layers:      overlay.layers,
651
            //             version:     overlay.version,
652
            //             transparent: overlay.transparent,
653
            //             format:      overlay.format
654
            //         }, {
655
            //             opacity:     parseFloat(overlay.opacity),
656
            //             visibility:  (overlay.visible).toLowerCase() == 'true',
657
            //             isBaseLayer: !1,
658
            //             attribution: overlay.attribution
659
            //         }
660
            //     ));
661
            //     break;
662
        }
663
    }
664
}
665
666
/** init. */
667
function olInit() {
668
    if (olEnable) {
0 ignored issues
show
If you intend to check if the variable olEnable is declared in the current environment, consider using typeof olEnable === "undefined" instead. This is safe if the variable is not actually declared.
Loading history...
669
        // add info window to DOM
670
        const frag = document.createDocumentFragment(),
671
            temp = document.createElement('div');
672
        temp.innerHTML = '<div id="popup" class="olPopup"><a href="#" id="popup-closer" class="olPopupCloseBox"></a><div id="popup-content"></div></div>';
673
        while (temp.firstChild) {
674
            frag.appendChild(temp.firstChild);
675
        }
676
        document.body.appendChild(frag);
677
678
        let _i = 0;
679
        // create the maps in the page
680
        for (_i = 0; _i < olMapData.length; _i++) {
0 ignored issues
show
The variable olMapData seems to be never declared. If this is a global, consider adding a /** global: olMapData */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
681
            const _id = olMapData[_i].mapOpts.id;
682
            olMaps[_id] = createMap(olMapData[_i].mapOpts, olMapData[_i].poi);
0 ignored issues
show
The variable olMaps seems to be never declared. If this is a global, consider adding a /** global: olMaps */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
683
684
            // set max-width on help pop-over
685
            jQuery('#' + _id).parent().parent().find('.olMapHelp').css('max-width', olMapData[_i].mapOpts.width);
686
687
            // shrink the map width to fit inside page container
688
            const _w = jQuery('#' + _id + '-olContainer').parent().innerWidth();
689
            if (parseInt(olMapData[_i].mapOpts.width) > _w) {
690
                jQuery('#' + _id).width(_w);
691
                jQuery('#' + _id).parent().parent().find('.olMapHelp').width(_w);
692
                olMaps[_id].updateSize();
693
            }
694
        }
695
696
        // add overlays
697
        olovAddToMap();
698
699
        let resizeTimer;
700
        jQuery(window).on('resize', function (e) {
0 ignored issues
show
The parameter e is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
701
            clearTimeout(resizeTimer);
702
            resizeTimer = setTimeout(function () {
703
                for (_i = 0; _i < olMapData.length; _i++) {
0 ignored issues
show
The variable olMapData seems to be never declared. If this is a global, consider adding a /** global: olMapData */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
The variable _i is changed as part of the for loop for example by _i++ on line 703. Only the value of the last iteration will be visible in this function if it is called after the loop.
Loading history...
704
                    const _id = olMapData[_i].mapOpts.id;
705
                    const _w = jQuery('#' + _id + '-olContainer').parent().innerWidth();
706
                    if (parseInt(olMapData[_i].mapOpts.width) > _w) {
707
                        jQuery('#' + _id).width(_w);
708
                        jQuery('#' + _id).parent().parent().find('.olMapHelp').width(_w);
709
                        olMaps[_id].updateSize();
0 ignored issues
show
The variable olMaps seems to be never declared. If this is a global, consider adding a /** global: olMaps */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
710
                    }
711
                }
712
            }, 250);
713
        });
714
715
        // hide the table(s) with POI by giving it a print-only style
716
        jQuery('.olPOItableSpan').addClass('olPrintOnly');
717
        // hide the static map image(s) by giving it a print only style
718
        jQuery('.olStaticMap').addClass('olPrintOnly');
719
        // add help button with toggle.
720
        jQuery('.olWebOnly > .olMap')
721
            .prepend(
722
                '<div class="olMapHelpButtonDiv">'
723
                + '<button onclick="jQuery(\'.olMapHelp\').toggle(500);" class="olMapHelpButton olHasTooltip"><span>'
724
                + 'Show or hide help</span>?</button></div>');
725
        // toggle to switch dynamic vs. static map
726
        jQuery('.olMapHelp').before(
727
            '<div class="a11y"><button onclick="jQuery(\'.olPrintOnly\').toggle();jQuery(\'.olWebOnly\').toggle();">'
728
            + 'Hide or show the dynamic map</button></div>');
729
    }
730
}
731
732
/**
733
 * CSS support flag.
734
 *
735
 * @type {Boolean}
736
 */
737
let olCSSEnable = true;
0 ignored issues
show
The variable olCSSEnable seems to be never used. Consider removing it.
Loading history...
738
739
/* register olInit to run with onload event. */
740
jQuery(olInit);
741