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