]> ToastFreeware Gitweb - philipp/winterrodeln/mediawiki_extensions/wrmap.git/blobdiff - wrmap.js
Include Polyfill for Internet Explorer directly instead of using a CDN.
[philipp/winterrodeln/mediawiki_extensions/wrmap.git] / wrmap.js
index f2e7fa171a5de3d7c29896a0ae2b1e467603df2b..f046114725101e83d5172adaddbd9c66a4e4a8ef 100644 (file)
--- a/wrmap.js
+++ b/wrmap.js
+"use strict";
+
 function init_wrmap(i, jq_map) {
+       // define constants
+       let EPSG4326 = ol.proj.get("EPSG:4326"); // lon/lat
+       let EPSG3857 = ol.proj.get("EPSG:3857"); // google
+
+       // tool functions
+       function createElement(tagName, attributes) {
+               let element = $(document.createElement(tagName));
+               if (attributes === undefined) return element;
+               for (let attribute in attributes) {
+                       element.attr(attribute, attributes[attribute]);
+               }
+               return element;
+       }
+
+       function appendElement(parentElement, tagName, attributes) {
+               if (attributes === undefined) attributes = {};
+               let element = createElement(tagName, attributes);
+               parentElement.append(element);
+               return element;
+       }
+
+
+       // extract geojson from map element and clear map element's content
        jq_map = $(jq_map);
-       OpenLayers.ImgPath = jq_map.attr('data-img-path'); // e.g. "/mediawiki/extensions/wrmap/openlayers/img/"
-       var jq_sledruns = jq_map.children();
-       jq_sledruns.detach();
-       
-       // Introduce EPSG:3857 as an alias of the built in EPSG:900913 projection (both are the "Google/OSM" projections)
-       var EPSG4326 = new OpenLayers.Projection("EPSG:4326"); // lon/lat 
-       var EPSG3857 = new OpenLayers.Projection("EPSG:3857"); // google
-
-       // Create the map
-       var map = new OpenLayers.Map(jq_map.context, {
-               projection: EPSG3857,
-               displayProjection: EPSG4326,
-               units: "m",
-               theme: null
-       });
+       let ext_path = jq_map.attr('data-ext-path'); // e.g. '/mediawiki/extensions/wrmap'
+       let img_path = ext_path + '/img';
+       let json_string = jq_map.children().last().text();
+       jq_map.empty(); // once parsed, remove geojson string from the map element.
+       let json_js = JSON.parse(json_string);
+       let format_geojson = new ol.format.GeoJSON();
+       let features_all = format_geojson.readFeatures(json_js, {dataProjection: EPSG4326, featureProjection: EPSG3857});
 
-       // Google Layer
-       var layer_map = new OpenLayers.Layer.Google("Google Physical", {
-               type: google.maps.MapTypeId.TERRAIN
-       });
 
-       // // Alternative: OSM map
-       // var layer_map = new OpenLayers.Layer.OSM();
-       
-       // // Alternative: Microsoft Bing Maps
-       // var layer_map = new OpenLayers.Layer.Bing({
-       //     type: "Road",
-       //     key: "AgPH3SlIXAwajrJKf0FORQyhTqsP8KIlvtN6RKfvxe6fOB6q6-HFmg8EOFm7LSOA"});
-       
-       // Sledrun layer
-       var layer_sledruns = new OpenLayers.Layer.Vector("Rodelbahnen", {
-               styleMap: new OpenLayers.StyleMap({
-                       "default": new OpenLayers.Style({
-                               externalGraphic: "/vorlagen/gmap_rodelbahn_c.png",
-                               graphicWidth: 17,
-                               graphicHeight: 17,
-                               graphicXOffset: -8,
-                               graphicYOffset: -8,
-                               graphicZIndex: 11,
-                               backgroundGraphic: "/vorlagen/gmap_rodelbahn_c_s.png",
-                               backgroundWidth: 23,
-                               backgroundHeight: 23,
-                               backgroundXOffset: -8,
-                               backgroundYOffset: -8,
-                               backgroundZIndex: 12,
-                               title: "${label}"
+       // path layer
+       // ----------
+
+       function get_feature_title(feature) {
+               let title = feature.get('type');
+               if (title == 'sledrun') return feature.get('name');
+               title = title.charAt(0).toUpperCase() + title.slice(1); // first letter uppercase
+               if (feature.get('name')) title += ': ' + feature.get('name');
+               return title;
+       }
+
+       // Returns 0 to 5 for features that represent sledruns as their condition
+       let get_sledrun_condition = function(feature) {
+               let condition = feature.get('condition');
+               if (condition === undefined) return 0;
+               return condition;
+       }
+
+       function sledrun_icon_style(condition, highlight) {
+               let hl = highlight ? 'h' : 'n';
+               let src = img_path + '/marker_c_sledrun_' + condition + 'n' + hl + '.png';
+               return new ol.style.Style({
+                       image: new ol.style.Icon({
+                               src: src,
+                               imgSize: [17, 17],
+                               anchor: [0.5, 0.5]
+                       }),
+               });
+
+       }
+
+       function sledrun_icon_shadow_style() {
+               return new ol.style.Style({
+                       image: new ol.style.Icon({
+                               src: img_path + '/marker_c_shadow.png',
+                               imgSize: [23, 23],
+                               anchor: [0.4, 0.4]
+                       }),
+               });
+       }
+
+       function marker_icon_style(feature) {
+               let src = img_path + '/marker_p_' + feature.get('type') + '.png';
+               return new ol.style.Style({
+                       image: new ol.style.Icon({
+                               src: src,
+                               imgSize: [20, 34],
+                               anchor: [0.5, 1.0]
                        }),
-                       "highlight": new OpenLayers.Style({
-                               label: "${label}",
-                               labelOutlineColor: "white",
-                               labelYOffset: 12,
-                               fontWeight: "bold"
+               });
+       }
+
+       function point_style(feature, highlight) {
+               let sledrun = feature.get('type') == 'sledrun';
+               let icon_style;
+               if (sledrun) {
+                       let condition = get_sledrun_condition(feature);
+                       icon_style = sledrun_icon_style(condition, highlight);
+               } else icon_style = marker_icon_style(feature);
+               if (highlight) {
+                       icon_style.setText(new ol.style.Text({
+                               text: get_feature_title(feature),
+                               font: 'icon',
+                               offsetY: 14,
+                               stroke: new ol.style.Stroke({
+                                       color: '#ddd',
+                                       width: 2,
+                               }),
+                       }));
+               }
+               if (sledrun) {
+                       let shadow_style = sledrun_icon_shadow_style();
+                       return [shadow_style, icon_style];
+               }
+               return [icon_style];
+       }
+
+       function style_point_function(feature, resolution) {
+               return point_style(feature, false);
+       }
+
+       function style_point_function_highlight(feature, resolution) {
+               return point_style(feature, true);
+       }
+
+       function style_path_function(feature, resolution) {
+               let line_color = {
+                       'rodelbahn': '#014e9a',
+                       'gehweg': '#e98401',
+                       'alternative': '#7f7fff',
+                       'lift': '#000000',
+                       'anfahrt': '#e1e100'
+               };
+               let color = feature.get('strokeColor') || line_color[feature.get('type')] || '#e7525b';
+               let width = (['lift', 'anfahrt'].indexOf(feature.get('type')) >= 0) ? 3 : 6;
+               return new ol.style.Style({
+                       stroke: new ol.style.Stroke({
+                               color: color,
+                               width: width
                        })
+               });
+       }
+
+       function style_function(feature, resolution) {
+               if (feature.getGeometry() instanceof ol.geom.Point) return style_point_function(feature, resolution);
+               return style_path_function(feature, resolution);
+       };
+
+       function style_function_highlight(feature, resolution) {
+               if (feature.getGeometry() instanceof ol.geom.Point) return style_point_function_highlight(feature, resolution);
+               return style_path_function(feature, resolution);
+       };
+
+
+       // popup overlay
+       // -------------
+       let popup_container = document.getElementById('popup');
+       let popup_content = document.getElementById('popup-content');
+       let popup_closer = document.getElementById('popup-closer');
+       let popup_overlay = new ol.Overlay({element: popup_container, autoPan: {animation: {duration: 250}}});
+       popup_closer.onclick = function() {popup_overlay.setPosition(undefined); popup_closer.blur(); return false;};
+
+       function create_popup_dom(feature) {
+               let popup_div = createElement('div');
+
+               // name
+               if (feature.get('name') !== undefined && (feature.get('wiki') !== undefined || feature.get('thumb_url') !== undefined)) {
+                       let h2 = appendElement(popup_div, 'h2');
+                       if (feature.get('wiki') === undefined) h2.text(feature.get('name'));
+                       else appendElement(h2, 'a', {href: feature.get('wiki')}).text(feature.get('name'));
+               }
+
+               // sledrun information
+               if (feature.get('type') == 'sledrun') {
+                       let p = appendElement(popup_div, 'p').text('Rodelbahnzustand').append(createElement('br'));
+                       if (feature.get('condition') !== undefined) {
+                               let condition_text = {1: 'Sehr gut', 2: 'Gut', 3: 'Mittelmäßig', 4: 'Schlecht', 5: 'Geht nicht'};
+                               let year_month_day = feature.get('date_report').split('-');
+                               p.append(createElement('a', {href: feature.get('wiki') + '#Eintr.C3.A4ge'}).text(condition_text[feature.get('condition')]), ' ');
+                               p.append(createElement('small').text(year_month_day[2] + '.' + year_month_day[1] + '.'), ' ');
+                               p.append(createElement('em').append(createElement('a', {href: feature.get('wiki') + '#Eintragen'}).text('Neu')));
+                       } else {
+                               p.append(createElement('em').append(createElement('a', {href: feature.get('wiki') + '#Eintragen'}).text('Bitte eintragen')));
+                       }
+               }
+
+               // wiki link
+               if (feature.get('wiki') !== undefined) {
+                       let a = appendElement(appendElement(popup_div, 'p'), 'a', {href: feature.get('wiki')});
+                       let detail_text = 'Details';
+                       if (feature.get('type') == 'sledrun') detail_text += ' zur Rodelbahn';
+                       if (feature.get('type') == 'gasthaus') detail_text += ' zum Gasthaus';
+                       if (feature.get('thumb_url') === undefined) a.text(detail_text);
+                       else a.append(createElement('img', {src: feature.get('thumb_url'), alt: detail_text, title: detail_text}));
+               }
+
+               return popup_div;
+       }
+
+
+       // map itself
+       // ----------
+       let lon = json_js.properties.lon;
+       let lat = json_js.properties.lat;
+       let zoom = json_js.properties.zoom;
+       let width = json_js.properties.width;
+       let height = json_js.properties.height;
+       if (zoom === undefined) zoom = 10; // default zoom
+       if (width === undefined) width = '100%'; // default width
+       if (height === undefined) height = 450;  // default: 450 pixel
+       jq_map.width(width);
+       jq_map.height(height);
+
+       let layer_sledrun_source = new ol.source.Vector({features: features_all});
+       let layer_sledrun = new ol.layer.Vector({
+               source: layer_sledrun_source,
+               style: style_function
+       });
+
+       let map = new ol.Map({
+               target: jq_map[0],
+               layers: [
+                       layer_sledrun
+               ],
+               overlays: [popup_overlay],
+               view: new ol.View({
+                       center: ol.proj.fromLonLat([lon, lat]),
+                       zoom: zoom
                }),
-               rendererOptions: {yOrdering: true}
+               controls: ol.control.defaults({
+                       attributionOptions: {
+                               collapsible: false
+                       }
+               }),
+               interactions: ol.interaction.defaults({
+                       mouseWheelZoom: false,
+                       dragPan: false,
+               }).extend([
+                       new ol.interaction.DragPan({
+                               condition: function (event) {
+                                       return this.getPointerCount() === 2 || ol.events.condition.platformModifierKeyOnly(event);
+                               },
+                       }),
+                       new ol.interaction.MouseWheelZoom({
+                               condition: ol.events.condition.platformModifierKeyOnly,
+                       }),
+                       new ol.interaction.Select({
+                               condition: ol.events.condition.pointerMove,
+                               style: style_function_highlight,
+                       })
+               ])
        });
-       jq_sledruns.each(function(j, jq_sledrun) {
-               jq_sledrun = $(jq_sledrun);
-               var lon = parseFloat(jq_sledrun.attr('data-lon'));
-               var lat = parseFloat(jq_sledrun.attr('data-lat'));
-               var point = new OpenLayers.Geometry.Point(lon, lat).transform(EPSG4326, EPSG3857);
-               layer_sledruns.addFeatures([new OpenLayers.Feature.Vector(point, {
-                       label: jq_sledrun.attr('data-title'),
-                       url: jq_sledrun.attr('data-url')
-               })]);
+
+       let select_click = new ol.interaction.Select({
+               condition: ol.events.condition.click,
+               style: false,
        });
-       map.addControl(new OpenLayers.Control.SelectFeature(layer_sledruns, {
-               hover: true,
-               highlightOnly: true,
-               autoActivate: true,
-               renderIntent: "highlight"
-       }));
-       map.addControl(new OpenLayers.Control.SelectFeature(layer_sledruns, {
-               autoActivate: true,
-               toggle: true,
-               onSelect: function(feature) {
-                       // Open popup
-                       var selectFeatureControl = this;
-                       var popup = new OpenLayers.Popup.FramedCloud("sledruninfopopup_" + feature.attributes['label'], 
-                       feature.geometry.getBounds().getCenterLonLat(),
-                       null,
-                       "<h2>" + feature.attributes['label'] + "</h2>\n" +
-                       "<ul>\n" + 
-                       "<li><a href=\"" + feature.attributes['url'] + "\">Details</a></li>\n" +
-                       "</ul>\n",
-                       null, true, function(event) {
-                               // onPopupClose
-                               selectFeatureControl.unselectAll();
-                       });
-                       feature.popup = popup;
-                       map.addPopup(popup);
-               },
-               onUnselect: function(feature) {
-                       // Close popup
-                       map.removePopup(feature.popup);
-                       feature.popup.destroy();
-                       feature.popup = null;
+       map.addInteraction(select_click);
+       select_click.on('select', function(event) {
+               if (event.selected.length > 0) {
+                       let feature = event.selected[0];
+                       let coordinates = feature.getGeometry().getCoordinates();
+                       let popup_dom = create_popup_dom(feature);
+                       if (popup_dom.children().length > 0) {
+                               $(popup_content).empty().append(popup_dom);
+                               popup_overlay.setPosition(coordinates);
+                       }
                }
-       }));
+       });
 
 
-       // Center map
-       map.addLayers([layer_map, layer_sledruns]);
-       var lon = parseFloat(jq_map.attr('data-center-lon'));
-       var lat = parseFloat(jq_map.attr('data-center-lat'));
-       var zoom = parseInt(jq_map.attr('data-zoom'));
-       map.setCenter(new OpenLayers.LonLat(lon, lat).transform(EPSG4326, map.getProjectionObject()), zoom);
+       // background layer
+       // ----------------
+       function get_austria_feature() {
+               // simplified "inner" polygon of Austria, created with tools/austria_simplified.py
+               let austria_wkt = 'POLYGON ((9.599 47.269, 9.767 47.523, 9.986 47.442, 10.192 47.234, 10.366 47.287, 10.488 47.497, ' +
+                       '10.814 47.477, 11.052 47.349, 11.732 47.539, 12.211 47.578, 12.269 47.656, 12.474 47.593, 12.676 47.622, ' +
+                       '12.839 47.471, 13.039 47.436, 13.120 47.661, 12.989 47.754, 13.019 47.900, 12.864 48.130, 13.419 48.328, ' +
+                       '13.516 48.523, 13.769 48.509, 13.867 48.699, 14.173 48.535, 14.726 48.561, 14.851 48.728, 14.983 48.751, ' +
+                       '15.036 48.954, 15.803 48.820, 16.041 48.711, 16.374 48.694, 16.496 48.754, 16.831 48.668, 16.800 48.376, ' +
+                       '17.050 48.001, 16.985 47.742, 16.583 47.795, 16.363 47.696, 16.605 47.538, 16.379 47.412, 16.402 47.043, ' +
+                       '15.994 46.879, 15.914 46.732, 14.874 46.649, 14.538 46.455, 12.501 46.715, 12.213 46.957, 12.267 47.065, ' +
+                       '12.181 47.126, 11.762 47.031, 11.220 47.018, 10.925 46.815, 10.520 46.900, 10.359 47.029, 10.134 46.899, ' +
+                       '9.674 47.095, 9.599 47.269))';
+               let format = new ol.format.WKT();
+               let feature = format.readFeature(austria_wkt, {
+                       dataProjection: EPSG4326,
+                       featureProjection: EPSG3857,
+               });
+               return feature;
+       }
 
+       // basemap.at layer
+       let austria_feature = get_austria_feature();
+       function is_in_austria(feature) {
+               return austria_feature.getGeometry().intersectsCoordinate(feature.getGeometry().getFirstCoordinate());
+       }
+       let austria_only = features_all.every(is_in_austria);
+       let capabilitiesUrl = austria_only ? 'https://maps.wien.gv.at/basemap/1.0.0/WMTSCapabilities.xml' : 'https://maps.wien.gv.at/vao/1.0.0/WMTSCapabilities.xml';
+       fetch(capabilitiesUrl).then(function(response) {
+               return response.text();
+       }).then(function(text) {
+               let result = new ol.format.WMTSCapabilities().read(text);
+               let options = ol.source.WMTS.optionsFromCapabilities(result, {
+                       layer: austria_only ? 'bmapgrau' : 'vaoausland',
+                       matrixSet: 'google3857',
+                       style: 'normal',
+               });
+               options['attributions'] = austria_only ? 'Grundkarte: <a href="https://www.basemap.at/">basemap.at</a>' : 'Grundkarte: <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>';
+               let layer_map = new ol.layer.Tile({
+                       source: new ol.source.WMTS(options),
+               });
+               map.getLayers().insertAt(0, layer_map);
+       });
+
+       // // Alternatives:
+       // // * OpenTopoMap (see https://opentopomap.org/about)
+       // // * OSM
+       // let layer_map = new ol.layer.Tile({
+       //     source: new ol.source.OSM()
+       // });
+       // map.getLayers().insertAt(0, layer_map);
 }
 
 
 function init_wrmaps() {
-       var jq_maps = $('.wrmap'); // all wrmap <div> elements
+       let jq_maps = $('.wrmap'); // all wrmap <div> elements
        jq_maps.each(init_wrmap);
 }
 
 
 $(document).ready(init_wrmaps);
-