]> ToastFreeware Gitweb - philipp/winterrodeln/mediawiki_extensions/wrmap.git/blob - src/wrmap.ts
Replace matrixSet with projection to be more general.
[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 Feature, { 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 OlSourceOsm from 'ol/source/OSM';
16 import OlLayerVector from 'ol/layer/Vector';
17 import OlLayerTile from 'ol/layer/Tile';
18 import { Geometry, SimpleGeometry as OlSimpleGeometry, SimpleGeometry } from 'ol/geom';
19 import OlPoint from 'ol/geom/Point';
20 import OlInteractionDragPan from 'ol/interaction/DragPan';
21 import OlInteractionMouseWheelZoom from 'ol/interaction/MouseWheelZoom';
22 import OlInteractionSelect from 'ol/interaction/Select';
23 import OlFormatWkt from 'ol/format/WKT';
24 import * as olEventsCondition from 'ol/events/condition';
25 import { defaults as olControlDefaults } from 'ol/control/defaults';
26 import { defaults as olInteractionDefaults } from 'ol/interaction/defaults';
27 import { get as olProjGet, fromLonLat } from 'ol/proj';
28
29
30 type SledrunCondition = number;
31
32
33
34 function init_wrmap(_: number, jq_map_element: HTMLElement) {
35         // define constants
36         let EPSG4326 = olProjGet("EPSG:4326")!; // lon/lat
37         let EPSG3857 = olProjGet("EPSG:3857")!; // google
38
39
40         interface StringStringHash {
41                 [key: string]: string
42         }
43
44         // tool functions
45         function createElement(tagName: string, attributes: StringStringHash = {}) {
46                 let element = $(document.createElement(tagName));
47                 for (let attribute in attributes) {
48                         element.attr(attribute, attributes[attribute]);
49                 }
50                 return element;
51         }
52
53
54         function appendElement(parentElement: JQuery<HTMLElement>, tagName: string, attributes: StringStringHash = {}) {
55                 let element = createElement(tagName, attributes);
56                 parentElement.append(element);
57                 return element;
58         }
59
60
61         // extract geojson from map element and clear map element's content
62         let jq_map = $(jq_map_element);
63         let ext_path = jq_map.attr('data-ext-path'); // e.g. '/mediawiki/extensions/wrmap'
64         let img_path = ext_path + '/img';
65         let json_string = jq_map.children().last().text();
66         jq_map.empty(); // once parsed, remove geojson string from the map element.
67         let json_js = JSON.parse(json_string);
68         let format_geojson = new OlGeoJson();
69         let features_all = format_geojson.readFeatures(json_js, {dataProjection: EPSG4326, featureProjection: EPSG3857});
70
71
72         // path layer
73         // ----------
74
75         function get_feature_title(feature: OlFeatureLike) {
76                 let title = feature.get('type');
77                 if (title == 'sledrun') return feature.get('name');
78                 title = title.charAt(0).toUpperCase() + title.slice(1); // first letter uppercase
79                 if (feature.get('name')) title += ': ' + feature.get('name');
80                 return title;
81         }
82
83
84         // Returns 0 to 5 for features that represent sledruns as their condition
85         let get_sledrun_condition = function(feature: OlFeatureLike): SledrunCondition {
86                 let condition = feature.get('condition');
87                 if (condition === undefined) return 0;
88                 return condition;
89         }
90
91
92         function sledrun_icon_style(condition: SledrunCondition, highlight: boolean) {
93                 let hl = highlight ? 'h' : 'n';
94                 let src = img_path + '/marker_c_sledrun_' + condition + 'n' + hl + '.png';
95                 return new OlStyle({
96                         image: new OlIcon({
97                                 src: src,
98                                 size: [17, 17],
99                                 anchor: [0.5, 0.5]
100                         }),
101                 });
102
103         }
104
105         function sledrun_icon_shadow_style() {
106                 return new OlStyle({
107                         image: new OlIcon({
108                                 src: img_path + '/marker_c_shadow.png',
109                                 size: [23, 23],
110                                 anchor: [0.4, 0.4]
111                         }),
112                 });
113         }
114
115         function marker_icon_style(feature: OlFeatureLike) {
116                 let src = img_path + '/marker_p_' + feature.get('type') + '.png';
117                 return new OlStyle({
118                         image: new OlIcon({
119                                 src: src,
120                                 size: [20, 34],
121                                 anchor: [0.5, 1.0]
122                         }),
123                 });
124         }
125
126
127         function point_style(feature: OlFeatureLike, highlight: boolean) {
128                 let sledrun = feature.get('type') == 'sledrun';
129                 let icon_style;
130                 if (sledrun) {
131                         let condition = get_sledrun_condition(feature);
132                         icon_style = sledrun_icon_style(condition, highlight);
133                 } else icon_style = marker_icon_style(feature);
134                 if (highlight) {
135                         icon_style.setText(new OlText({
136                                 text: get_feature_title(feature),
137                                 font: 'icon',
138                                 offsetY: 14,
139                                 stroke: new OlStroke({
140                                         color: '#ddd',
141                                         width: 2,
142                                 }),
143                         }));
144                 }
145                 if (sledrun) {
146                         let shadow_style = sledrun_icon_shadow_style();
147                         return [shadow_style, icon_style];
148                 }
149                 return [icon_style];
150         }
151
152
153         function style_point_function(feature: OlFeatureLike, _resolution: number) {
154                 return point_style(feature, false);
155         }
156
157
158         function style_point_function_highlight(feature: OlFeatureLike, _resolution: number) {
159                 return point_style(feature, true);
160         }
161
162
163         function style_path_function(feature: OlFeatureLike, _resolution: number) {
164                 let line_color = {
165                         'rodelbahn': '#014e9a',
166                         'gehweg': '#e98401',
167                         'alternative': '#7f7fff',
168                         'lift': '#000000',
169                         'anfahrt': '#e1e100'
170                 };
171                 let featureType: keyof(typeof line_color) = feature.get('type');
172                 let color = feature.get('strokeColor') || line_color[featureType] || '#e7525b';
173                 let width = (['lift', 'anfahrt'].indexOf(feature.get('type')) >= 0) ? 3 : 6;
174                 return new OlStyle({
175                         stroke: new OlStroke({
176                                 color: color,
177                                 width: width
178                         })
179                 });
180         }
181
182
183         function style_function(feature: OlFeatureLike, resolution: number) {
184                 if (feature.getGeometry() instanceof OlPoint) return style_point_function(feature, resolution);
185                 return style_path_function(feature, resolution);
186         };
187
188
189         function style_function_highlight(feature: OlFeatureLike, resolution: number) {
190                 if (feature.getGeometry() instanceof OlPoint) return style_point_function_highlight(feature, resolution);
191                 return style_path_function(feature, resolution);
192         };
193
194
195         // popup overlay
196         // -------------
197
198         let popup_container = document.createElement('div');
199         popup_container.setAttribute('class', 'ol-popup');
200         popup_container = jq_map_element.insertAdjacentElement('afterend', popup_container) as HTMLDivElement;
201         let popup_closer = document.createElement('a');
202         popup_closer.setAttribute('href', '#');
203         popup_closer.setAttribute('class', 'ol-popup-closer');
204         popup_closer = popup_container.insertAdjacentElement('beforeend', popup_closer) as HTMLAnchorElement;
205         let popup_content = document.createElement('div');
206         popup_content = popup_container.insertAdjacentElement('beforeend', popup_content) as HTMLDivElement;
207         let popup_overlay = new OlOverlay({element: popup_container, autoPan: {animation: {duration: 250}}});
208         popup_closer.onclick = function() {popup_overlay.setPosition(undefined); popup_closer.blur(); return false;};
209
210
211         function create_popup_dom(feature: OlFeatureLike) {
212                 let popup_div = createElement('div');
213
214                 // name
215                 if (feature.get('name') !== undefined && (feature.get('wiki') !== undefined || feature.get('thumb_url') !== undefined)) {
216                         let h2 = appendElement(popup_div, 'h2');
217                         if (feature.get('wiki') === undefined) h2.text(feature.get('name'));
218                         else appendElement(h2, 'a', {href: new mw.Title(feature.get('wiki')).getUrl({})}).text(feature.get('name'));
219                 }
220
221                 // sledrun information
222                 if (feature.get('type') == 'sledrun') {
223                         let p = appendElement(popup_div, 'p').text('Rodelbahnzustand').append(createElement('br'));
224                         let wiki_title = new mw.Title(feature.get('wiki'));
225                         if (feature.get('condition') !== undefined) {
226                                 let condition_text = {1: 'Sehr gut', 2: 'Gut', 3: 'Mittelmäßig', 4: 'Schlecht', 5: 'Geht nicht'};
227                                 let condition: keyof(typeof condition_text) = feature.get('condition');
228                                 let year_month_day = feature.get('date_report').split('-');
229                                 p.append(createElement('a', {href: wiki_title.getUrl({}) + '#Eintr.C3.A4ge'}).text(condition_text[condition]), ' ');
230                                 p.append(createElement('small').text(year_month_day[2] + '.' + year_month_day[1] + '.'), ' ');
231                                 p.append(createElement('em').append(createElement('a', {href: wiki_title.getUrl({}) + '#Eintragen'}).text('Neu')));
232                         } else {
233                                 p.append(createElement('em').append(createElement('a', {href: wiki_title.getUrl({}) + '#Eintragen'}).text('Bitte eintragen')));
234                         }
235                 }
236
237                 // wiki link
238                 if (feature.get('wiki') !== undefined) {
239                         let a = appendElement(appendElement(popup_div, 'p'), 'a', {href: new mw.Title(feature.get('wiki')).getUrl({})});
240                         let detail_text = 'Details';
241                         if (feature.get('type') == 'sledrun') detail_text += ' zur Rodelbahn';
242                         if (feature.get('type') == 'gasthaus') detail_text += ' zum Gasthaus';
243                         if (feature.get('thumb_url') !== undefined) {
244                                 a.append(createElement('img', {src: feature.get('thumb_url'), alt: detail_text, title: detail_text}));
245                         } else {
246                                 a.text(detail_text);
247                                 // query thumbnail info like: /mediawiki/api.php?action=query&prop=pageimages&pithumbsize=200&titles=Rumer%20Alm%20(Gasthaus)
248                                 let api = new mw.Api();
249                                 api.get( {
250                                         action: 'query',
251                                         prop: 'pageimages',
252                                         pithumbsize: '200',
253                                         titles: feature.get('wiki')
254                                 }).done( function ( data ) {
255                                         let pages = data?.query?.pages;
256                                         if (pages instanceof Object) {
257                                                 for (let pageNumber in pages) {
258                                                         let page = pages[pageNumber];
259                                                         let thumbnail = page.thumbnail;
260                                                         if (thumbnail instanceof Object) {
261                                                                 a.empty();
262                                                                 a.append(createElement('img', {src: thumbnail.source, alt: detail_text, title: detail_text, width: thumbnail.width, height: thumbnail.height}));
263                                                                 popup_overlay.panIntoView();
264                                                         }
265                                                 }
266                                         }
267                                 });
268                         }
269                 }
270
271                 return popup_div;
272         }
273
274
275         // map itself
276         // ----------
277         let lon = json_js.wr_properties?.lon ?? 11.;
278         let lat = json_js.wr_properties?.lat ?? 47.;
279         let zoom = json_js.wr_properties?.zoom ?? 10;
280         let width = json_js.wr_properties?.width ?? '100%';
281         let height = json_js.properties?.height ?? 450;
282         jq_map.width(width);
283         jq_map.height(height);
284
285         let layer_sledrun_source = new OlSourceVector({features: features_all});
286         let layer_sledrun = new OlLayerVector({
287                 source: layer_sledrun_source,
288                 style: style_function
289         });
290
291         let center = fromLonLat([lon, lat]);
292         let map = new OlMap({
293                 target: jq_map[0],
294                 layers: [
295                         layer_sledrun
296                 ],
297                 overlays: [popup_overlay],
298                 view: new OlView({
299                         center: center,
300                         zoom: zoom
301                 }),
302                 controls: olControlDefaults({
303                         attributionOptions: {
304                                 collapsible: false
305                         }
306                 }),
307                 interactions: olInteractionDefaults({
308                         mouseWheelZoom: false,
309                         dragPan: false,
310                 }).extend([
311                         new OlInteractionDragPan({
312                                 condition: function (event) {
313                                         let dragPan = this as OlInteractionDragPan;
314                                         return dragPan.getPointerCount() === 2 || olEventsCondition.platformModifierKeyOnly(event);
315                                 },
316                         }),
317                         new OlInteractionMouseWheelZoom({
318                                 condition: olEventsCondition.platformModifierKeyOnly,
319                         }),
320                         new OlInteractionSelect({
321                                 condition: olEventsCondition.pointerMove,
322                                 style: style_function_highlight,
323                         })
324                 ])
325         });
326
327         let select_click = new OlInteractionSelect({
328                 condition: olEventsCondition.click,
329                 style: null,
330         });
331         map.addInteraction(select_click);
332         select_click.on('select', function(event) {
333                 if (event.selected.length > 0) {
334                         let feature: OlFeatureLike = event.selected[0];
335                         let geometry = feature.getGeometry() as OlSimpleGeometry;
336                         let coordinates = geometry.getFirstCoordinate();
337                         let popup_dom = create_popup_dom(feature);
338                         if (popup_dom.children().length > 0) {
339                                 $(popup_content).empty().append(popup_dom);
340                                 popup_overlay.setPosition(coordinates);
341                         }
342                 }
343         });
344
345
346         // background layer
347         // ----------------
348
349         // simplified "inner" polygon of Austria, created with tools/simplify_country.py --country Austria
350         const austriaWkt = '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, ' +
351                 '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, ' +
352                 '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, ' +
353                 '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, ' +
354                 '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, ' +
355                 '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, ' +
356                 '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, ' +
357                 '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, ' +
358                 '9.674 47.095, 9.599 47.269))';
359
360         // simplified "inner" polygon of Swiss, created with tools/simplify_country.py --country Switzerland
361         const swissWkt = 'MULTIPOLYGON (((6.041 46.190, 6.146 46.251, 6.168 46.295, 6.195 46.258, 6.041 46.190)), ' +
362                 '((6.186 46.362, 6.130 46.442, 6.213 46.583, 6.465 46.731, 6.504 46.914, 7.007 47.242, 7.013 47.419, 7.364 47.390, ' +
363                 '7.620 47.543, 8.470 47.553, 8.632 47.620, 8.487 47.700, 8.569 47.729, 8.867 47.612, 9.163 47.626, 9.555 47.450, ' +
364                 '9.420 47.182, 9.449 47.026, 9.795 46.973, 10.117 46.808, 10.389 46.891, 10.376 46.593, 10.204 46.666, ' +
365                 '10.027 46.618, 9.973 46.481, 10.057 46.312, 9.888 46.413, 9.567 46.345, 9.465 46.519, 9.214 46.507, 9.187 46.298, ' +
366                 '8.941 46.027, 8.970 45.881, 8.867 46.107, 8.515 46.269, 8.440 46.489, 8.045 46.299, 8.062 46.176, 7.818 45.986, ' +
367                 '7.530 46.023, 7.136 45.928, 6.843 46.173, 6.792 46.454, 6.412 46.474, 6.186 46.362)))';
368
369         const bolzanoWkt = 'POLYGON ((10.452 46.680, 10.501 46.800, 11.012 46.725, 11.202 46.923, 11.743 46.926, ' +
370                 '12.047 47.001, 12.072 46.884, 12.335 46.673, 12.058 46.706, 11.973 46.577, 11.654 46.548, 11.534 46.402, ' +
371                 '11.232 46.285, 11.242 46.540, 10.650 46.499, 10.452 46.680))'
372
373
374         function getCountryGeometry(countryWkt: string) {
375                 let format = new OlFormatWkt();
376                 let geometry = format.readGeometry(countryWkt, {
377                         dataProjection: EPSG4326,
378                         featureProjection: EPSG3857,
379                 });
380                 return geometry;
381         }
382
383
384         const austria = getCountryGeometry(austriaWkt);
385         const swiss = getCountryGeometry(swissWkt);
386         const bolzano = getCountryGeometry(bolzanoWkt);
387
388
389         function insertWmtsLayer(capabilitiesUrl: string, layer: string, attributions: string) {
390                 fetch(capabilitiesUrl).then(function(response) {
391                         return response.text();
392                 }).then(function(text) {
393                         let result = new OlFormatWmtsCapabilities().read(text);
394                         let options = optionsFromCapabilities(result, {
395                                 layer: layer,
396                                 projection: 'EPSG:3857',
397                                 style: 'normal',
398                         })!;
399                         options['attributions'] = attributions;
400                         let layer_map = new OlLayerTile({
401                                 source: new OlSourceWmts(options),
402                         });
403                         map.getLayers().insertAt(0, layer_map);
404                 });
405         }
406
407
408         function insertSwissLayer() {
409                 // Swiss OpenStreetMap Association https://sosm.ch/projects/tile-service/
410                 let layer_map = new OlLayerTile({
411                         source: new OlSourceOsm({
412                                 attributions: '© OpenStreetMap contributors, Elevation: ASTER GDEM, EarthEnv-DEM90, CDEM contains information under OGL Canada',
413                                 url: 'https://tile.osm.ch/switzerland/{z}/{x}/{y}.png'
414                         }),
415                 });
416                 map.getLayers().insertAt(0, layer_map);
417         }
418
419
420         function allFeaturesInCountry(features: Feature<Geometry>[], country: Geometry): boolean {
421                 return features.every(function (feature: Feature<Geometry>) {return country.intersectsCoordinate((feature.getGeometry() as SimpleGeometry).getFirstCoordinate())});
422         }
423
424         enum BackgroundLayer {
425                 BasemapAt,
426                 VaoAusland,
427                 Sosm,
428                 Bolzano,
429         }
430
431         let backgroundLayer = BackgroundLayer.BasemapAt;
432
433         if (allFeaturesInCountry(features_all, austria)) {
434                 backgroundLayer = BackgroundLayer.BasemapAt;
435         } else if (allFeaturesInCountry(features_all, swiss)) {
436                 backgroundLayer = BackgroundLayer.Sosm;
437         } else if (allFeaturesInCountry(features_all, bolzano)) {
438                 backgroundLayer = BackgroundLayer.Bolzano;
439         } else if (swiss.intersectsCoordinate(center)) {
440                 backgroundLayer = BackgroundLayer.Sosm;
441         } else {
442                 backgroundLayer = BackgroundLayer.VaoAusland;
443         }
444
445         switch (backgroundLayer) {
446                 case BackgroundLayer.BasemapAt:
447                         insertWmtsLayer('https://mapsneu.wien.gv.at/basemapneu/1.0.0/WMTSCapabilities.xml', 'bmapgrau', 'Grundkarte: <a href="https://www.basemap.at/">basemap.at</a>');
448                         break;
449                 case BackgroundLayer.VaoAusland:
450                         insertWmtsLayer('https://mapsneu.wien.gv.at/vaoneu/1.0.0/WMTSCapabilities.xml', 'vaoausland', 'Grundkarte: <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>');
451                         break;
452                 case BackgroundLayer.Sosm:
453                         insertSwissLayer();
454                         break;
455                 case BackgroundLayer.Bolzano:
456                         insertWmtsLayer('https://geoservices.buergernetz.bz.it/mapproxy/service?REQUEST=GetCapabilities&SERVICE=WMTS', 'oown-OpenStreetMap:Terrain', 'Grundkarte: <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>');
457                         break;
458         }
459
460
461         // // Alternatives:
462         // // * OpenTopoMap (see https://opentopomap.org/about)
463         // // * OSM
464         // let layer_map = new OlLayerTile({
465         //     source: new OlSourceOsm()
466         // });
467
468 }
469
470
471 function init_wrmaps() {
472         let jq_maps = $('.wrmap'); // all wrmap <div> elements
473         jq_maps.each(init_wrmap);
474 }
475
476
477 $(init_wrmaps);