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