]> ToastFreeware Gitweb - philipp/winterrodeln/mediawiki_extensions/wrmap.git/blob - src/wrmap.ts
Auto-generate CSS as well.
[philipp/winterrodeln/mediawiki_extensions/wrmap.git] / src / wrmap.ts
1 import './wrmap.css'
2 import OlMap from '../node_modules/ol/Map';
3 import OlView from '../node_modules/ol/View';
4 import OlStyle from '../node_modules/ol/style/Style';
5 import OlStroke from '../node_modules/ol/style/Stroke';
6 import OlText from '../node_modules/ol/style/Text';
7 import OlIcon from '../node_modules/ol/style/Icon';
8 import OlGeoJson from '../node_modules/ol/format/GeoJSON';
9 import OlOverlay from '../node_modules/ol/Overlay';
10 import OlSourceVector from '../node_modules/ol/source/Vector';
11 import OlSourceWmts from '../node_modules/ol/source/WMTS';
12 import OlFormatWmtsCapabilities from '../node_modules/ol/format/WMTSCapabilities';
13 import { optionsFromCapabilities } from 'ol/source/WMTS';
14 import OlLayerVector from '../node_modules/ol/layer/Vector';
15 import OlLayerTile from '../node_modules/ol/layer/Tile';
16 import OlPoint from '../node_modules/ol/geom/Point';
17 import OlInteractionDragPan from '../node_modules/ol/interaction/DragPan';
18 import OlInteractionMouseWheelZoom from '../node_modules/ol/interaction/MouseWheelZoom';
19 import OlInteractionSelect from '../node_modules/ol/interaction/Select';
20 import OlFormatWkt from '../node_modules/ol/format/WKT';
21 import * as olEventsCondition from '../node_modules/ol/events/condition';
22 import { defaults as olControlDefaults } from '../node_modules/ol/control/defaults';
23 import { defaults as olInteractionDefaults } from '../node_modules/ol/interaction/defaults';
24 import { get as olProjGet, fromLonLat } from '../node_modules/ol/proj';
25
26
27
28 function init_wrmap(_: number, jq_map: JQuery<HTMLElement>) {
29         // define constants
30         let EPSG4326 = olProjGet("EPSG:4326"); // lon/lat
31         let EPSG3857 = olProjGet("EPSG:3857"); // google
32
33         // tool functions
34         function createElement(tagName: string, attributes) {
35                 let element = $(document.createElement(tagName));
36                 if (attributes === undefined) return element;
37                 for (let attribute in attributes) {
38                         element.attr(attribute, attributes[attribute]);
39                 }
40                 return element;
41         }
42
43         function appendElement(parentElement, tagName: string, attributes) {
44                 if (attributes === undefined) attributes = {};
45                 let element = createElement(tagName, attributes);
46                 parentElement.append(element);
47                 return element;
48         }
49
50
51         // extract geojson from map element and clear map element's content
52         jq_map = $(jq_map);
53         let ext_path = jq_map.attr('data-ext-path'); // e.g. '/mediawiki/extensions/wrmap'
54         let img_path = ext_path + '/img';
55         let json_string = jq_map.children().last().text();
56         jq_map.empty(); // once parsed, remove geojson string from the map element.
57         let json_js = JSON.parse(json_string);
58         let format_geojson = new OlGeoJson();
59         let features_all = format_geojson.readFeatures(json_js, {dataProjection: EPSG4326, featureProjection: EPSG3857});
60
61
62         // path layer
63         // ----------
64
65         function get_feature_title(feature) {
66                 let title = feature.get('type');
67                 if (title == 'sledrun') return feature.get('name');
68                 title = title.charAt(0).toUpperCase() + title.slice(1); // first letter uppercase
69                 if (feature.get('name')) title += ': ' + feature.get('name');
70                 return title;
71         }
72
73         // Returns 0 to 5 for features that represent sledruns as their condition
74         let get_sledrun_condition = function(feature) {
75                 let condition = feature.get('condition');
76                 if (condition === undefined) return 0;
77                 return condition;
78         }
79
80         function sledrun_icon_style(condition, highlight: boolean) {
81                 let hl = highlight ? 'h' : 'n';
82                 let src = img_path + '/marker_c_sledrun_' + condition + 'n' + hl + '.png';
83                 return new OlStyle({
84                         image: new OlIcon({
85                                 src: src,
86                                 imgSize: [17, 17],
87                                 anchor: [0.5, 0.5]
88                         }),
89                 });
90
91         }
92
93         function sledrun_icon_shadow_style() {
94                 return new OlStyle({
95                         image: new OlIcon({
96                                 src: img_path + '/marker_c_shadow.png',
97                                 imgSize: [23, 23],
98                                 anchor: [0.4, 0.4]
99                         }),
100                 });
101         }
102
103         function marker_icon_style(feature) {
104                 let src = img_path + '/marker_p_' + feature.get('type') + '.png';
105                 return new OlStyle({
106                         image: new OlIcon({
107                                 src: src,
108                                 imgSize: [20, 34],
109                                 anchor: [0.5, 1.0]
110                         }),
111                 });
112         }
113
114         function point_style(feature, highlight: boolean) {
115                 let sledrun = feature.get('type') == 'sledrun';
116                 let icon_style;
117                 if (sledrun) {
118                         let condition = get_sledrun_condition(feature);
119                         icon_style = sledrun_icon_style(condition, highlight);
120                 } else icon_style = marker_icon_style(feature);
121                 if (highlight) {
122                         icon_style.setText(new OlText({
123                                 text: get_feature_title(feature),
124                                 font: 'icon',
125                                 offsetY: 14,
126                                 stroke: new OlStroke({
127                                         color: '#ddd',
128                                         width: 2,
129                                 }),
130                         }));
131                 }
132                 if (sledrun) {
133                         let shadow_style = sledrun_icon_shadow_style();
134                         return [shadow_style, icon_style];
135                 }
136                 return [icon_style];
137         }
138
139         function style_point_function(feature, resolution) {
140                 return point_style(feature, false);
141         }
142
143         function style_point_function_highlight(feature, resolution) {
144                 return point_style(feature, true);
145         }
146
147         function style_path_function(feature, resolution) {
148                 let line_color = {
149                         'rodelbahn': '#014e9a',
150                         'gehweg': '#e98401',
151                         'alternative': '#7f7fff',
152                         'lift': '#000000',
153                         'anfahrt': '#e1e100'
154                 };
155                 let color = feature.get('strokeColor') || line_color[feature.get('type')] || '#e7525b';
156                 let width = (['lift', 'anfahrt'].indexOf(feature.get('type')) >= 0) ? 3 : 6;
157                 return new OlStyle({
158                         stroke: new OlStroke({
159                                 color: color,
160                                 width: width
161                         })
162                 });
163         }
164
165         function style_function(feature, resolution) {
166                 if (feature.getGeometry() instanceof OlPoint) return style_point_function(feature, resolution);
167                 return style_path_function(feature, resolution);
168         };
169
170         function style_function_highlight(feature, resolution) {
171                 if (feature.getGeometry() instanceof OlPoint) return style_point_function_highlight(feature, resolution);
172                 return style_path_function(feature, resolution);
173         };
174
175
176         // popup overlay
177         // -------------
178         let popup_container = document.getElementById('popup');
179         let popup_content = document.getElementById('popup-content');
180         let popup_closer = document.getElementById('popup-closer');
181         let popup_overlay = new OlOverlay({element: popup_container, autoPan: {animation: {duration: 250}}});
182         popup_closer.onclick = function() {popup_overlay.setPosition(undefined); popup_closer.blur(); return false;};
183
184         function create_popup_dom(feature) {
185                 let popup_div = createElement('div');
186
187                 // name
188                 if (feature.get('name') !== undefined && (feature.get('wiki') !== undefined || feature.get('thumb_url') !== undefined)) {
189                         let h2 = appendElement(popup_div, 'h2');
190                         if (feature.get('wiki') === undefined) h2.text(feature.get('name'));
191                         else appendElement(h2, 'a', {href: new mw.Title(feature.get('wiki')).getUrl()}).text(feature.get('name'));
192                 }
193
194                 // sledrun information
195                 if (feature.get('type') == 'sledrun') {
196                         let p = appendElement(popup_div, 'p').text('Rodelbahnzustand').append(createElement('br'));
197                         let wiki_title = new mw.Title(feature.get('wiki'));
198                         if (feature.get('condition') !== undefined) {
199                                 let condition_text = {1: 'Sehr gut', 2: 'Gut', 3: 'Mittelmäßig', 4: 'Schlecht', 5: 'Geht nicht'};
200                                 let year_month_day = feature.get('date_report').split('-');
201                                 p.append(createElement('a', {href: wiki_title.getUrl() + '#Eintr.C3.A4ge'}).text(condition_text[feature.get('condition')]), ' ');
202                                 p.append(createElement('small').text(year_month_day[2] + '.' + year_month_day[1] + '.'), ' ');
203                                 p.append(createElement('em').append(createElement('a', {href: wiki_title.getUrl() + '#Eintragen'}).text('Neu')));
204                         } else {
205                                 p.append(createElement('em').append(createElement('a', {href: wiki_title.getUrl() + '#Eintragen'}).text('Bitte eintragen')));
206                         }
207                 }
208
209                 // wiki link
210                 if (feature.get('wiki') !== undefined) {
211                         let a = appendElement(appendElement(popup_div, 'p'), 'a', {href: new mw.Title(feature.get('wiki')).getUrl()});
212                         let detail_text = 'Details';
213                         if (feature.get('type') == 'sledrun') detail_text += ' zur Rodelbahn';
214                         if (feature.get('type') == 'gasthaus') detail_text += ' zum Gasthaus';
215                         if (feature.get('thumb_url') === undefined) a.text(detail_text);
216                         else a.append(createElement('img', {src: feature.get('thumb_url'), alt: detail_text, title: detail_text}));
217                 }
218
219                 return popup_div;
220         }
221
222
223         // map itself
224         // ----------
225         let lon = json_js.properties.lon;
226         let lat = json_js.properties.lat;
227         let zoom = json_js.properties.zoom;
228         let width = json_js.properties.width;
229         let height = json_js.properties.height;
230         if (zoom === undefined) zoom = 10; // default zoom
231         if (width === undefined) width = '100%'; // default width
232         if (height === undefined) height = 450;  // default: 450 pixel
233         jq_map.width(width);
234         jq_map.height(height);
235
236         let layer_sledrun_source = new OlSourceVector({features: features_all});
237         let layer_sledrun = new OlLayerVector({
238                 source: layer_sledrun_source,
239                 style: style_function
240         });
241
242         let map = new OlMap({
243                 target: jq_map[0],
244                 layers: [
245                         layer_sledrun
246                 ],
247                 overlays: [popup_overlay],
248                 view: new OlView({
249                         center: fromLonLat([lon, lat]),
250                         zoom: zoom
251                 }),
252                 controls: olControlDefaults({
253                         attributionOptions: {
254                                 collapsible: false
255                         }
256                 }),
257                 interactions: olInteractionDefaults({
258                         mouseWheelZoom: false,
259                         dragPan: false,
260                 }).extend([
261                         new OlInteractionDragPan({
262                                 condition: function (event) {
263                                         return this.getPointerCount() === 2 || olEventsCondition.platformModifierKeyOnly(event);
264                                 },
265                         }),
266                         new OlInteractionMouseWheelZoom({
267                                 condition: olEventsCondition.platformModifierKeyOnly,
268                         }),
269                         new OlInteractionSelect({
270                                 condition: olEventsCondition.pointerMove,
271                                 style: style_function_highlight,
272                         })
273                 ])
274         });
275
276         let select_click = new OlInteractionSelect({
277                 condition: olEventsCondition.click,
278                 style: false,
279         });
280         map.addInteraction(select_click);
281         select_click.on('select', function(event) {
282                 if (event.selected.length > 0) {
283                         let feature = event.selected[0];
284                         let coordinates = feature.getGeometry().getCoordinates();
285                         let popup_dom = create_popup_dom(feature);
286                         if (popup_dom.children().length > 0) {
287                                 $(popup_content).empty().append(popup_dom);
288                                 popup_overlay.setPosition(coordinates);
289                         }
290                 }
291         });
292
293
294         // background layer
295         // ----------------
296         function get_austria_feature() {
297                 // simplified "inner" polygon of Austria, created with tools/austria_simplified.py
298                 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, ' +
299                         '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, ' +
300                         '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, ' +
301                         '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, ' +
302                         '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, ' +
303                         '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, ' +
304                         '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, ' +
305                         '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, ' +
306                         '9.674 47.095, 9.599 47.269))';
307                 let format = new OlFormatWkt();
308                 let feature = format.readFeature(austria_wkt, {
309                         dataProjection: EPSG4326,
310                         featureProjection: EPSG3857,
311                 });
312                 return feature;
313         }
314
315         // basemap.at layer
316         let austria_feature = get_austria_feature();
317         function is_in_austria(feature) {
318                 return austria_feature.getGeometry().intersectsCoordinate(feature.getGeometry().getFirstCoordinate());
319         }
320         let austria_only = features_all.every(is_in_austria);
321         let capabilitiesUrl = austria_only ? 'https://mapsneu.wien.gv.at/basemapneu/1.0.0/WMTSCapabilities.xml' : 'https://mapsneu.wien.gv.at/vaoneu/1.0.0/WMTSCapabilities.xml';
322         fetch(capabilitiesUrl).then(function(response) {
323                 return response.text();
324         }).then(function(text) {
325                 let result = new OlFormatWmtsCapabilities().read(text);
326                 let options = optionsFromCapabilities(result, {
327                         layer: austria_only ? 'bmapgrau' : 'vaoausland',
328                         matrixSet: 'google3857',
329                         style: 'normal',
330                 });
331                 options['attributions'] = austria_only ? 'Grundkarte: <a href="https://www.basemap.at/">basemap.at</a>' : 'Grundkarte: <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>';
332                 let layer_map = new OlLayerTile({
333                         source: new OlSourceWmts(options),
334                 });
335                 map.getLayers().insertAt(0, layer_map);
336         });
337
338         // // Alternatives:
339         // // * OpenTopoMap (see https://opentopomap.org/about)
340         // // * OSM
341         // let layer_map = new ol.layer.Tile({
342         //     source: new ol.source.OSM()
343         // });
344         // map.getLayers().insertAt(0, layer_map);
345 }
346
347
348 function init_wrmaps() {
349         let jq_maps = $('.wrmap'); // all wrmap <div> elements
350         jq_maps.each(init_wrmap);
351 }
352
353
354 $(document).ready(
355         function() {setTimeout(init_wrmaps, 1000);} // we need to delay that since otherwise the map is not shown in sections collapsed by MobileFrontent
356 );
357
358
359 // export = init_wrmap;