1/*
2 * Copyright (c) 2008-2023 Mark C. Prins <mprins@users.sf.net>
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 */
26function 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 */
41function 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 */
70function createMap(mapOpts, poi) {
71
72    // const mapOpts = olMapData[0].mapOpts;
73    // const poi = olMapData[0].poi;
74    const autoZoom_options = {padding: [16, 16, 16, 16]};
75
76    if (!olEnable) {
77        return null;
78    }
79    if (!olTestCSSsupport()) {
80        olEnable = false;
81        return null;
82    }
83
84    // find map element location
85    const cleartag = document.getElementById(mapOpts.id + '-clearer');
86    if (cleartag === null) {
87        return null;
88    }
89    // create map element and add to document
90    const fragment = olCreateMaptag(mapOpts.id, mapOpts.width, mapOpts.height);
91    cleartag.parentNode.insertBefore(fragment, cleartag);
92
93    /** dynamic map extent. */
94    let extent = ol.extent.createEmpty();
95    let overlayGroup = new ol.layer.Group({title: 'Overlays', fold: 'open', layers: []});
96    const baseLyrGroup = new ol.layer.Group({'title': 'Base maps', layers: []});
97
98    const map = new ol.Map({
99        target: document.getElementById(mapOpts.id),
100        layers: [baseLyrGroup, overlayGroup],
101        view: new ol.View({
102            center: ol.proj.transform([mapOpts.lon, mapOpts.lat], 'EPSG:4326', 'EPSG:3857'),
103            zoom: mapOpts.zoom,
104            projection: 'EPSG:3857'
105        }),
106        controls: [
107            new ol.control.Attribution({
108                collapsible: true,
109                collapsed: true
110            })
111        ]
112    });
113
114    if (osmEnable) {
115        baseLyrGroup.getLayers().push(
116            new ol.layer.Tile({
117                visible: true,
118                title: 'OSM',
119                type: 'base',
120                source: new ol.source.OSM()
121            }));
122
123        baseLyrGroup.getLayers().push(
124            new ol.layer.Tile({
125                visible: mapOpts.baselyr === "opentopomap",
126                title: 'opentopomap',
127                type: 'base',
128                source: new ol.source.OSM({
129                    url: 'https://{a-c}.tile.opentopomap.org/{z}/{x}/{y}.png',
130                    attributions: 'Data &copy;ODbL <a href="https://openstreetmap.org/copyright" target="_blank">OpenStreetMap</a>, '
131                        + '<a href="http://viewfinderpanoramas.org" target="_blank">SRTM</a>, '
132                        + 'style &copy;<a href="https://opentopomap.org/" target="_blank">OpenTopoMap</a>'
133                        + '(<a href="https://creativecommons.org/licenses/by-sa/3.0/">CC-BY-SA</a>)'
134                })
135            }));
136
137        baseLyrGroup.getLayers().push(
138            new ol.layer.Tile({
139                visible: mapOpts.baselyr === "cycle map",
140                title: 'cycle map',
141                type: 'base',
142                source: new ol.source.OSM({
143                    url: 'https://{a-c}.tile.thunderforest.com/cycle/{z}/{x}/{y}.png?apikey=' + tfApiKey,
144                    attributions: 'Data &copy;ODbL <a href="https://openstreetmap.org/copyright" target="_blank">OpenStreetMap</a>, '
145                        + 'Tiles &copy;<a href="https://www.thunderforest.com/" target="_blank">Thunderforest</a>'
146                        + '<img src="https://www.thunderforest.com/favicon.ico" alt="Thunderforest logo"/>'
147                })
148            }));
149
150        baseLyrGroup.getLayers().push(
151            new ol.layer.Tile({
152                visible: mapOpts.baselyr === "transport",
153                title: 'transport',
154                type: 'base',
155                source: new ol.source.OSM({
156                    url: 'https://{a-c}.tile.thunderforest.com/transport/{z}/{x}/{y}.png?apikey=' + tfApiKey,
157                    attributions: 'Data &copy;ODbL <a href="https://openstreetmap.org/copyright" target="_blank">OpenStreetMap</a>, '
158                        + 'Tiles &copy;<a href="https://www.thunderforest.com/" target="_blank">Thunderforest</a>'
159                        + '<img src="https://www.thunderforest.com/favicon.ico" alt="Thunderforest logo"/>'
160                })
161            }));
162
163        baseLyrGroup.getLayers().push(
164            new ol.layer.Tile({
165                visible: mapOpts.baselyr === "landscape",
166                title: 'landscape',
167                type: 'base',
168                source: new ol.source.OSM({
169                    url: 'https://{a-c}.tile.thunderforest.com/landscape/{z}/{x}/{y}.png?apikey=' + tfApiKey,
170                    attributions: 'Data &copy;ODbL <a href="https://openstreetmap.org/copyright" target="_blank">OpenStreetMap</a>, '
171                        + 'Tiles &copy;<a href="https://www.thunderforest.com/" target="_blank">Thunderforest</a>'
172                        + '<img src="https://www.thunderforest.com/favicon.ico" alt="Thunderforest logo"/>'
173                })
174            }));
175
176        baseLyrGroup.getLayers().push(
177            new ol.layer.Tile({
178                visible: mapOpts.baselyr === "outdoors",
179                title: 'outdoors',
180                type: 'base',
181                source: new ol.source.OSM({
182                    url: 'https://{a-c}.tile.thunderforest.com/outdoors/{z}/{x}/{y}.png?apikey=' + tfApiKey,
183                    attributions: 'Data &copy;ODbL <a href="https://openstreetmap.org/copyright" target="_blank">OpenStreetMap</a>, '
184                        + 'Tiles &copy;<a href="https://www.thunderforest.com/" target="_blank">Thunderforest</a>'
185                        + '<img src="https://www.thunderforest.com/favicon.ico" alt="Thunderforest logo"/>'
186                })
187            }));
188    }
189
190    if (bEnable && bApiKey !== '') {
191        baseLyrGroup.getLayers().push(
192            new ol.layer.Tile({
193                visible: mapOpts.baselyr === "bing road",
194                title: 'bing road',
195                type: 'base',
196                source: new ol.source.BingMaps({
197                    key: bApiKey,
198                    imagerySet: 'Road'
199                })
200            }));
201
202        baseLyrGroup.getLayers().push(
203            new ol.layer.Tile({
204                visible: mapOpts.baselyr === "bing sat",
205                title: 'bing sat',
206                type: 'base',
207                source: new ol.source.BingMaps({
208                    key: bApiKey,
209                    imagerySet: 'Aerial'
210                })
211            }));
212
213        baseLyrGroup.getLayers().push(
214            new ol.layer.Tile({
215                visible: mapOpts.baselyr === "bing hybrid",
216                title: 'bing hybrid',
217                type: 'base',
218                source: new ol.source.BingMaps({
219                    key: bApiKey,
220                    imagerySet: 'AerialWithLabels'
221                })
222            }));
223    }
224
225    if (stadiaEnable) {
226        baseLyrGroup.getLayers().push(
227            new ol.layer.Tile({
228                visible: mapOpts.baselyr === "toner",
229                type: 'base',
230                title: 'toner',
231                // apiKey: 'OPTIONAL', (we suggest domain-based auth)
232                source: new ol.source.StadiaMaps({
233                    layer: 'stamen_toner',
234                    // missing CORS header
235                    // url:'https://tiles-eu.stadiamaps.com/tiles/'
236                })
237            })
238        );
239
240        baseLyrGroup.getLayers().push(
241            new ol.layer.Tile({
242                visible: mapOpts.baselyr === "terrain",
243                type: 'base',
244                title: 'terrain',
245                // apiKey: 'OPTIONAL', (we suggest domain-based auth)
246                source: new ol.source.StadiaMaps({
247                    layer: 'stamen_terrain',
248                    // missing CORS header
249                    // url:'https://tiles-eu.stadiamaps.com/tiles/'
250                })
251            })
252        );
253    }
254
255    extent = ol.extent.extend(extent, map.getView().calculateExtent());
256
257    const iconScale = window.devicePixelRatio ?? 1.0;
258    const vectorSource = new ol.source.Vector();
259    poi.forEach((p) => {
260        const f = new ol.Feature({
261            geometry: new ol.geom.Point(ol.proj.fromLonLat([p.lon, p.lat])),
262            description: p.txt,
263            img: p.img,
264            rowId: p.rowId,
265            lat: p.lat,
266            lon: p.lon,
267            angle: p.angle,
268            opacity: p.opacity,
269            alt: p.img.substring(0, p.img.lastIndexOf("."))
270        });
271        f.setId(p.rowId);
272        vectorSource.addFeature(f);
273    });
274
275    const vectorLayer = new ol.layer.Vector({
276        title: 'POI',
277        visible: true,
278        source: vectorSource,
279        style(feature, resolution) {
280            const img = feature.get('img');
281            const opacity = feature.get('opacity');
282            const angle = feature.get('angle');
283            const text = feature.get('rowId');
284
285            return new ol.style.Style({
286                image: new ol.style.Icon({
287                    src: `${DOKU_BASE}lib/plugins/openlayersmap/icons/${img}`,
288                    crossOrigin: '',
289                    opacity: opacity,
290                    scale: iconScale,
291                    rotation: angle * Math.PI / 180,
292                    // width/height were added in OpenLayers 7.2.2
293                    // see https://github.com/openlayers/openlayers/pull/14364
294                }),
295                text: new ol.style.Text({
296                    text: `${text}`,
297                    textAlign: 'center',
298                    textBaseline: 'middle',
299                    offsetX: (8 + 4 + 2) * iconScale,
300                    offsetY: -8 * iconScale,
301                    scale: iconScale,
302                    fill: new ol.style.Fill({color: 'rgb(0,0,0)'}),
303                    font: 'bold 16px monospace',
304                    stroke: new ol.style.Stroke({color: 'rgba(255,255,255,.4)', width: 5}),
305                })
306            });
307        }
308    });
309    overlayGroup.getLayers().push(vectorLayer);
310    if (mapOpts.autozoom) {
311        extent = ol.extent.extend(extent, vectorSource.getExtent());
312        map.getView().fit(extent, autoZoom_options);
313    }
314
315    if (mapOpts.controls === 1) {
316        map.addControl(new ol.control.Zoom());
317        map.addControl(new ol.control.ScaleLine({bar: true, text: true}));
318        map.addControl(new ol.control.MousePosition({
319            coordinateFormat: ol.coordinate.createStringXY(4), projection: 'EPSG:4326',
320        }));
321        map.addControl(new ol.control.FullScreen({
322            // Square Four Corners / U+26F6
323            label: '⛶',
324            labelActive: '▢'
325        }));
326        map.addControl(new ol.control.OverviewMap({
327            label: '+',
328            layers: [new ol.layer.Tile({
329                source: new ol.source.OSM()
330            })]
331        }));
332        map.addControl(new ol.control.LayerSwitcher({
333            activationMode: 'click',
334            label: '\u2630',
335            collapseLabel: '\u00BB',
336        }));
337    }
338
339    if (mapOpts.kmlfile.length > 0) {
340        try {
341            const kmlSource = new ol.source.Vector({
342                url: DOKU_BASE + "lib/exe/fetch.php?media=" + mapOpts.kmlfile,
343                format: new ol.format.KML(),
344            });
345            overlayGroup.getLayers().push(new ol.layer.Vector({title: 'KML file', visible: true, source: kmlSource}));
346
347            if (mapOpts.autozoom) {
348                kmlSource.once('change', function () {
349                    extent = ol.extent.extend(extent, kmlSource.getExtent());
350                    map.getView().fit(extent, autoZoom_options);
351                });
352            }
353        } catch (e) {
354            console.error(e);
355        }
356    }
357
358    if (mapOpts.geojsonfile.length > 0) {
359        try {
360            // these are the same colour as in StaticMap#drawJSON()
361            const geoJsonStyle = {
362                'Point': new ol.style.Style({
363                    image: new ol.style.Circle({
364                        fill: new ol.style.Fill({
365                            color: 'rgba(255,0,255,0.4)',
366                        }),
367                        radius: 5,
368                        stroke: new ol.style.Stroke({
369                            color: 'rgba(255,0,255,0.9)',
370                            width: 1,
371                        }),
372                    }),
373                }),
374                'LineString': new ol.style.Style({
375                    stroke: new ol.style.Stroke({
376                        color: 'rgba(255,0,255,0.9)',
377                        width: 3,
378                    }),
379                }),
380                'MultiLineString': new ol.style.Style({
381                    stroke: new ol.style.Stroke({
382                        color: 'rgba(255,0,255,0.9)',
383                        width: 3,
384                    }),
385                }),
386                'Polygon': new ol.style.Style({
387                    stroke: new ol.style.Stroke({
388                        color: 'rgba(255,0,255,0.9)',
389                        width: 3,
390                    }),
391                    fill: new ol.style.Fill({
392                        color: 'rgba(255,0,255,0.4)',
393                    }),
394                }),
395                'MultiPolygon': new ol.style.Style({
396                    stroke: new ol.style.Stroke({
397                        color: 'rgba(255,0,255,0.9)',
398                        width: 3,
399                    }),
400                    fill: new ol.style.Fill({
401                        color: 'rgba(255,0,255,0.4)',
402                    }),
403                }),
404            };
405            const geoJsonSource = new ol.source.Vector({
406                url: DOKU_BASE + "lib/exe/fetch.php?media=" + mapOpts.geojsonfile,
407                format: new ol.format.GeoJSON(),
408            });
409            overlayGroup.getLayers().push(new ol.layer.Vector({
410                title: 'GeoJSON file', visible: true, source: geoJsonSource,
411                style: function (feature) {
412                    return geoJsonStyle[feature.getGeometry().getType()];
413                },
414            }));
415
416            if (mapOpts.autozoom) {
417                geoJsonSource.once('change', function () {
418                    extent = ol.extent.extend(extent, geoJsonSource.getExtent());
419                    map.getView().fit(extent, autoZoom_options);
420                });
421            }
422        } catch (e) {
423            console.error(e);
424        }
425    }
426
427    if (mapOpts.gpxfile.length > 0) {
428        try {
429            // these are the same colour as in StaticMap#drawGPX()
430            const gpxJsonStyle = {
431                'Point': new ol.style.Style({
432                    image: new ol.style.Circle({
433                        fill: new ol.style.Fill({
434                            color: 'rgba(0,0,255,0.4)',
435                        }),
436                        radius: 5,
437                        stroke: new ol.style.Stroke({
438                            color: 'rgba(0,0,255,0.9)',
439                            width: 1,
440                        }),
441                    }),
442                }),
443                'LineString': new ol.style.Style({
444                    stroke: new ol.style.Stroke({
445                        color: 'rgba(0,0,255,0.9)',
446                        width: 3,
447                    }),
448                }),
449                'MultiLineString': new ol.style.Style({
450                    stroke: new ol.style.Stroke({
451                        color: 'rgba(0,0,255,0.9)',
452                        width: 3,
453                    }),
454                }),
455            };
456            const gpxSource = new ol.source.Vector({
457                url: DOKU_BASE + "lib/exe/fetch.php?media=" + mapOpts.gpxfile,
458                format: new ol.format.GPX(),
459            });
460            overlayGroup.getLayers().push(new ol.layer.Vector({
461                title: 'GPS track', visible: true, source: gpxSource,
462                style: function (feature) {
463                    return gpxJsonStyle[feature.getGeometry().getType()];
464                },
465            }));
466
467            if (mapOpts.autozoom) {
468                gpxSource.once('change', function () {
469                    extent = ol.extent.extend(extent, gpxSource.getExtent());
470                    map.getView().fit(extent, autoZoom_options);
471                });
472            }
473        } catch (e) {
474            console.error(e);
475        }
476    }
477
478    const container = document.getElementById('popup');
479    const content = document.getElementById('popup-content');
480    const closer = document.getElementById('popup-closer');
481
482    const overlay = new ol.Overlay({
483        element: container,
484        positioning: 'center-center',
485        stopEvent: true,
486        autoPan: {
487            animation: {
488                duration: 250,
489            }
490        },
491    });
492    map.addOverlay(overlay);
493
494    /**
495     * Add a click handler to hide the popup.
496     * @return {boolean} Don't follow the href.
497     */
498    closer.onclick = function () {
499        overlay.setPosition(undefined);
500        closer.blur();
501        return false;
502    };
503
504    // display popup on click
505    map.on('singleclick', function (evt) {
506        const selFeature = map.forEachFeatureAtPixel(evt.pixel, function (feature) {
507            return feature;
508        });
509        if (selFeature) {
510            overlay.setPosition(evt.coordinate);
511
512            let pContent = '<div class="spacer">&nbsp;</div>';
513            // let locDesc = '';
514
515            if (selFeature.get('rowId') !== undefined) {
516                pContent += '<span class="rowId">' + selFeature.get('rowId') + ': </span>';
517            }
518            if (selFeature.get('name') !== undefined) {
519                pContent += '<span class="txt">' + selFeature.get('name') + '</span>';
520                // locDesc = selFeature.get('name');
521                // TODO strip <p> tag from locDesc
522                // locDesc = selFeature.get('name').split(/\s+/).slice(0,2).join('+');
523            }
524            if (selFeature.get('ele') !== undefined) {
525                pContent += '<div class="ele">elevation: ' + selFeature.get('ele') + '</div>';
526            }
527            if (selFeature.get('type') !== undefined) {
528                pContent += '<div>' + selFeature.get('type') + '</div>';
529            }
530            if (selFeature.get('time') !== undefined) {
531                pContent += '<div class="time">time: ' + selFeature.get('time') + '</div>';
532            }
533            if (selFeature.get('description') !== undefined) {
534                pContent += '<div class="desc">' + selFeature.get('description') + '</div>';
535            }
536            if (selFeature.get('img') !== undefined) {
537                const _alt = selFeature.get('alt');
538                // Android Maps intent: https://developer.android.com/guide/components/intents-common#Maps
539                // geo uri scheme: https://en.wikipedia.org/wiki/Geo_URI_scheme
540                // geo uri reference: https://tools.ietf.org/html/rfc5870
541                // OSM wiki: https://wiki.openstreetmap.org/wiki/Geo_URI_scheme
542                pContent += '<div class="coord" title="lat;lon">' +
543                    '<img alt="' + _alt + '" src="' + DOKU_BASE + 'lib/plugins/openlayersmap/icons/' + selFeature.get('img') +
544                    '" width="16" height="16" ' + 'style="transform:rotate(' + selFeature.get('angle') + 'deg)" />&nbsp;' +
545                    '<a href="geo:' + selFeature.get('lat') + ','
546                    + selFeature.get('lon') +
547                    '?q=' + selFeature.get('lat') + ',' +
548                    selFeature.get('lon') +
549                    '&name=' + selFeature.get('alt') +
550                    ';z=16" title="Open in navigation app">' +
551                    ol.coordinate.format([selFeature.get('lon'), selFeature.get('lat')], '{x}º; {y}º', 4)
552                    + '</a>' +
553                    '</div>';
554            }
555            content.innerHTML = pContent;
556        } else {
557            // do nothing...
558        }
559    });
560
561    // change mouse cursor when over marker
562    map.on('pointermove', function (e) {
563        const pixel = map.getEventPixel(e.originalEvent);
564        const hit = map.hasFeatureAtPixel(pixel);
565        map.getTarget().style.cursor = hit ? 'pointer' : '';
566    });
567
568    return map;
569}
570
571/**
572 * add layers to the map based on the olMapOverlays object.
573 */
574function olovAddToMap() {
575    for (const key in olMapOverlays) {
576        const overlay = olMapOverlays[key];
577        const m = olMaps[overlay.id];
578
579        let targetGroup;
580        const isBaselayer = overlay.baselayer && (overlay.baselayer).toLowerCase() === 'true';
581        m.getLayers().forEach(function (layer) {
582            if (layer.get('title') === 'Base maps' && isBaselayer) {
583                targetGroup = layer;
584            }
585            if (layer.get('title') === 'Overlays' && !isBaselayer) {
586                targetGroup = layer;
587            }
588        });
589
590        switch (overlay.type) {
591            case 'osm':
592                targetGroup.getLayers().push(new ol.layer.Tile({
593                    title: overlay.name,
594                    visible: (overlay.visible).toLowerCase() === 'true',
595                    opacity: parseFloat(overlay.opacity),
596                    source: new ol.source.OSM({
597                        url: overlay.url,
598                        crossOrigin: 'Anonymous',
599                        attributions: overlay.attribution
600                    }),
601                    type: overlay.baselayer ? 'base' : 'overlay'
602                }));
603                break;
604            case 'wms':
605                targetGroup.getLayers().push(new ol.layer.Image({
606                    title: overlay.name,
607                    opacity: parseFloat(overlay.opacity),
608                    visible: (overlay.visible).toLowerCase() === 'true',
609                    source: new ol.source.ImageWMS({
610                        url: overlay.url,
611                        params: {
612                            'LAYERS': overlay.layers,
613                            'VERSION': overlay.version,
614                            'TRANSPARENT': overlay.transparent,
615                            'FORMAT': overlay.format
616                        },
617                        ratio: 1,
618                        crossOrigin: 'Anonymous',
619                        attributions: overlay.attribution
620                    }),
621                    type: overlay.baselayer ? 'base' : 'overlay'
622                }));
623                break;
624            case 'wmts':
625                const parser = new ol.format.WMTSCapabilities();
626                fetch(overlay.url).then(function (response) {
627                    return response.text();
628                }).then(function (text) {
629                    const wmtsCap = parser.read(text);
630                    const options = ol.source.WMTS.optionsFromCapabilities(wmtsCap, {
631                        layer: overlay.layer,
632                        matrixSet: overlay.matrixSet
633                    });
634                    options.crossOrigin = 'Anonymous';
635                    options.attributions = overlay.attribution;
636                    targetGroup.getLayers().push(new ol.layer.Tile({
637                        title: overlay.name,
638                        opacity: parseFloat(overlay.opacity),
639                        visible: (overlay.visible).toLowerCase() === 'true',
640                        source: new ol.source.WMTS(options),
641                        type: overlay.baselayer ? 'base' : 'overlay'
642                    }));
643                });
644                break;
645            case 'ags':
646                targetGroup.getLayers().push(new ol.layer.Image({
647                    title: overlay.name,
648                    opacity: parseFloat(overlay.opacity),
649                    visible: (overlay.visible).toLowerCase() === 'true',
650                    source: new ol.source.ImageArcGISRest({
651                        url: overlay.url,
652                        params: {
653                            'LAYERS': overlay.layers,
654                            'TRANSPARENT': overlay.transparent,
655                            'FORMAT': overlay.format
656                        },
657                        ratio: 1,
658                        crossOrigin: 'Anonymous',
659                        attributions: overlay.attribution,
660                        type: overlay.baselayer ? 'base' : 'overlay'
661                    })
662                }));
663                break;
664            // case 'mapillary':
665            //     var mUrl = 'http://api.mapillary.com/v1/im/search?';
666            //     if (overlay.skey !== '') {
667            //         mUrl = 'http://api.mapillary.com/v1/im/sequence?';
668            //     }
669            //     var mLyr = new OpenLayers.Layer.Vector(
670            //         "Mapillary", {
671            //             projection:  new OpenLayers.Projection("EPSG:4326"),
672            //             strategies:  [new OpenLayers.Strategy.BBOX({
673            //                 ratio:     1.1,
674            //                 resFactor: 1.5
675            //             }) /* ,new OpenLayers.Strategy.Cluster({}) */],
676            //             protocol:    new OpenLayers.Protocol.HTTP({
677            //                 url:            mUrl,
678            //                 format:         new OpenLayers.Format.GeoJSON(),
679            //                 params:         {
680            //                     // default to max. 250 locations
681            //                     'max-results': 250,
682            //                     'geojson':     true,
683            //                     'skey':        overlay.skey
684            //                 },
685            //                 filterToParams: function (filter, params) {
686            //                     if (filter.type === OpenLayers.Filter.Spatial.BBOX) {
687            //                         // override the bbox serialization of
688            //                         // the filter to give the Mapillary
689            //                         // specific bounds
690            //                         params['min-lat'] = filter.value.bottom;
691            //                         params['max-lat'] = filter.value.top;
692            //                         params['min-lon'] = filter.value.left;
693            //                         params['max-lon'] = filter.value.right;
694            //                         // if the width of our bbox width is
695            //                         // less than 0.15 degrees drop the max
696            //                         // results
697            //                         if (filter.value.top - filter.value.bottom < .15) {
698            //                             OpenLayers.Console.debug('dropping max-results parameter, width is: ',
699            //                                 filter.value.top - filter.value.bottom);
700            //                             params['max-results'] = null;
701            //                         }
702            //                     }
703            //                     return params;
704            //                 }
705            //             }),
706            //             styleMap:    new OpenLayers.StyleMap({
707            //                 'default': {
708            //                     cursor:          'help',
709            //                     rotation:        '${ca}',
710            //                     externalGraphic: DOKU_BASE + 'lib/plugins/openlayersmapoverlays/icons/arrow-up-20.png',
711            //                     graphicHeight:   20,
712            //                     graphicWidth:    20,
713            //                 },
714            //                 'select':  {
715            //                     externalGraphic: DOKU_BASE + 'lib/plugins/openlayersmapoverlays/icons/arrow-up-20-select.png',
716            //                     label:           '${location}',
717            //                     fontSize:        '1em',
718            //                     fontFamily:      'monospace',
719            //                     labelXOffset:    '0.5',
720            //                     labelYOffset:    '0.5',
721            //                     labelAlign:      'lb',
722            //                 }
723            //             }),
724            //             attribution: '<a href="http://www.mapillary.com/legal.html">' +
725            //                              '<img src="http://mapillary.com/favicon.ico" ' +
726            //                              'alt="Mapillary" height="16" width="16" />Mapillary (CC-BY-SA)',
727            //             visibility:  (overlay.visible).toLowerCase() == 'true',
728            //         });
729            //     m.addLayer(mLyr);
730            //     selectControl.addLayer(mLyr);
731            //     break;
732            // case 'search':
733            //     m.addLayer(new OpenLayers.Layer.Vector(
734            //         overlay.name,
735            //         overlay.url,
736            //         {
737            //             layers:      overlay.layers,
738            //             version:     overlay.version,
739            //             transparent: overlay.transparent,
740            //             format:      overlay.format
741            //         }, {
742            //             opacity:     parseFloat(overlay.opacity),
743            //             visibility:  (overlay.visible).toLowerCase() == 'true',
744            //             isBaseLayer: !1,
745            //             attribution: overlay.attribution
746            //         }
747            //     ));
748            //     break;
749        }
750    }
751}
752
753/** init. */
754function olInit() {
755    if (typeof olEnable !== 'undefined' && olEnable) {
756        // add info window to DOM
757        const frag = document.createDocumentFragment(),
758            temp = document.createElement('div');
759        temp.innerHTML = '<div id="popup" class="olPopup"><a href="#" id="popup-closer" class="olPopupCloseBox"></a><div id="popup-content"></div></div>';
760        while (temp.firstChild) {
761            frag.appendChild(temp.firstChild);
762        }
763        document.body.appendChild(frag);
764
765        let _i = 0;
766        // create the maps in the page
767        for (_i = 0; _i < olMapData.length; _i++) {
768            const _id = olMapData[_i].mapOpts.id;
769            olMaps[_id] = createMap(olMapData[_i].mapOpts, olMapData[_i].poi);
770
771            // set max-width on help pop-over
772            jQuery('#' + _id).parent().parent().find('.olMapHelp').css('max-width', olMapData[_i].mapOpts.width);
773
774            // shrink the map width to fit inside page container
775            const _w = jQuery('#' + _id + '-olContainer').parent().innerWidth();
776            if (parseInt(olMapData[_i].mapOpts.width) > _w) {
777                jQuery('#' + _id).width(_w);
778                jQuery('#' + _id).parent().parent().find('.olMapHelp').width(_w);
779                olMaps[_id].updateSize();
780            }
781        }
782
783        // add overlays
784        olovAddToMap();
785
786        let resizeTimer;
787        jQuery(window).on('resize', function (e) {
788            clearTimeout(resizeTimer);
789            resizeTimer = setTimeout(function () {
790                for (_i = 0; _i < olMapData.length; _i++) {
791                    const _id = olMapData[_i].mapOpts.id;
792                    const _w = jQuery('#' + _id + '-olContainer').parent().innerWidth();
793                    if (parseInt(olMapData[_i].mapOpts.width) > _w) {
794                        jQuery('#' + _id).width(_w);
795                        jQuery('#' + _id).parent().parent().find('.olMapHelp').width(_w);
796                        olMaps[_id].updateSize();
797                    }
798                }
799            }, 250);
800        });
801
802        // hide the table(s) with POI by giving it a print-only style
803        jQuery('.olPOItableSpan').addClass('olPrintOnly');
804        // hide the static map image(s) by giving it a print only style
805        jQuery('.olStaticMap').addClass('olPrintOnly');
806        // add help button with toggle.
807        jQuery('.olWebOnly > .olMap')
808            .prepend(
809                '<div class="olMapHelpButtonDiv">'
810                + '<button onclick="jQuery(\'.olMapHelp\').toggle(500);" class="olMapHelpButton olHasTooltip"><span>'
811                + 'Show or hide help</span>?</button></div>');
812        // toggle to switch dynamic vs. static map
813        jQuery('.olMapHelp').before(
814            '<div class="a11y"><button onclick="jQuery(\'.olPrintOnly\').toggle();jQuery(\'.olWebOnly\').toggle();">'
815            + 'Hide or show the dynamic map</button></div>');
816    }
817}
818
819/**
820 * CSS support flag.
821 *
822 * @type {Boolean}
823 */
824let olCSSEnable = true;
825
826/* register olInit to run with onload event. */
827jQuery(olInit);
828