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