878b70982faa1cec46f186d855b6d901e2ca8a63
[philipp/winterrodeln/mediawiki_extensions/wrmap.git] / wrmap.js
1 "use strict";
2 /*
3 // "User defined" popup class to be able to specify a minimum size for the popup,
4 // so that Safari 7.0 displays it correctly (see ticket #89).
5 OpenLayers.Popup.WrInfo = OpenLayers.Class(OpenLayers.Popup.FramedCloud, {
6         minSize: new OpenLayers.Size(180, 260),
7
8         initialize: function(id, lonlat, contentSize, contentHTML, anchor, closeBox, closeCallback) {
9                 OpenLayers.Popup.FramedCloud.prototype.initialize.apply(this, arguments);
10         },
11
12         CLASS_NAME: "OpenLayers.Popup.WrInfo"
13 });
14 */
15
16
17 function init_wrmap(i, jq_map) {
18         // define constants
19         var EPSG4326 = ol.proj.get("EPSG:4326"); // lon/lat
20         var EPSG3857 = ol.proj.get("EPSG:3857"); // google
21
22         /*
23         // tool functions
24         function createElement(tagName, attributes) {
25                 var element = $(document.createElement(tagName));
26                 if (attributes === undefined) return element;
27                 for (var attribute in attributes) {
28                         element.attr(attribute, attributes[attribute]);
29                 }
30                 return element;
31         }
32
33         function appendElement(parentElement, tagName, attributes) {
34                 if (attributes === undefined) attributes = {};
35                 var element = createElement(tagName, attributes);
36                 parentElement.append(element);
37                 return element;
38         }
39         */
40
41
42         // extract geojson from map element and clear map element's content
43         jq_map = $(jq_map);
44         var ext_path = jq_map.attr('data-ext-path'); // e.g. '/mediawiki/extensions/wrmap'
45         var img_path = ext_path + '/img';
46         //OpenLayers.ImgPath = ext_path + '/openlayers/img/'; // e.g. '/mediawiki/extensions/wrmap/openlayers/img/'
47         var json_string = jq_map.children().last().text();
48         jq_map.empty(); // once parsed, remove geojson string from the map element.
49         var json_js = JSON.parse(json_string);
50         var format_geojson = new ol.format.GeoJSON();
51         var features_all = format_geojson.readFeatures(json_js, {dataProjection: EPSG4326, featureProjection: EPSG3857});
52
53         // extract, tranform and split features to layers
54         /*
55         var features_path = new Array();
56         var features_point = new Array();
57         for (var i = 0; i != features_all.length; ++i) {
58                 var feature = features_all[i];
59                 feature.geometry.transform(EPSG4326, EPSG3857);
60                 if (feature.geometry instanceof OpenLayers.Geometry.Point) features_point.push(feature);
61                 else features_path.push(feature);
62         }
63         */
64
65         // background layer
66         // ----------------
67
68         // OSM map
69         var layer_map = new ol.layer.Tile({
70                 source: new ol.source.OSM()
71         });
72
73
74         /*
75         // Microsoft Bing Maps
76         // var layer_map = new OpenLayers.Layer.Bing({
77         //      type: "Road",
78         //      key: "AgPH3SlIXAwajrJKf0FORQyhTqsP8KIlvtN6RKfvxe6fOB6q6-HFmg8EOFm7LSOA",
79         //      tileOptions: {crossOriginKeyword: null}});
80
81         // // Alternative: Base map
82         // // see: http://www.basemap.at
83         
84         // // Alternative: OpenTopoMap
85         // // see: https://opentopomap.org/about
86
87         // // Alternative: Dummy base layer
88         // var layer_map = new OpenLayers.Layer.Vector("Base Layer", {
89         //     isBaseLayer: true});
90         */
91
92
93         // path layer
94         // ----------
95
96         function get_feature_title(feature) {
97                 var title = feature.get('type');
98                 if (title == 'sledrun') return feature.get('name');
99                 title = title.charAt(0).toUpperCase() + title.slice(1); // first letter uppercase
100                 if (feature.get('name')) title += ': ' + feature.get('name');
101                 return title;
102         }
103
104         // Returns 0 to 5 for features that represent sledruns as their condition
105         var get_sledrun_condition = function(feature) {
106                 var condition = feature.get('condition');
107                 if (condition === undefined) return 0;
108                 return condition;
109         }
110
111         function style_point_function(feature, resolution) {
112                 if (feature.get('type') == 'sledrun') {
113                         var condition = get_sledrun_condition(feature);
114                         var src = img_path + '/marker_c_sledrun_' + condition + 'nn.png';
115                         return new ol.style.Style({
116                                 image: new ol.style.Icon({
117                                         src: src,
118                                         imgSize: [17, 17],
119                                         anchor: [0.5, 0.5]
120                                 }),
121                         });
122                 } else {
123                         var src = img_path + '/marker_p_' + feature.get('type') + '.png';
124                         return new ol.style.Style({
125                                 image: new ol.style.Icon({
126                                         src: src,
127                                         imgSize: [20, 34],
128                                         anchor: [0.5, 1.0]
129                                 }),
130                         });
131                 }
132         }
133
134         function style_point_function_selected(feature, resolution) {
135                 var style = style_point_function(feature, resolution);
136                 style.setText(new ol.style.Text({
137                         text: get_feature_title(feature),
138                         font: 'icon',
139                         offsetY: 14,
140                         stroke: new ol.style.Stroke({
141                                 color: '#ddd',
142                                 width: 2,
143                         }),
144                 }));
145                 return style;
146         }
147
148         function style_path_function(feature, resolution) {
149                 var line_color = {
150                         'rodelbahn': '#014e9a',
151                         'gehweg': '#e98401',
152                         'alternative': '#7f7fff',
153                         'lift': '#000000',
154                         'anfahrt': '#e1e100'
155                 };
156                 var color = feature.get('strokeColor') || line_color[feature.get('type')] || '#e7525b';
157                 var width = (feature.get('type') in ['lift', 'anfahrt']) ? 3 : 6;
158                 return new ol.style.Style({
159                         stroke: new ol.style.Stroke({
160                                 color: color,
161                                 width: width
162                         })
163                 });
164         }
165
166         function style_function(feature, resolution) {
167                 if (feature.getGeometry() instanceof ol.geom.Point) return style_point_function(feature, resolution);
168                 return style_path_function(feature, resolution);
169         };
170
171         function style_function_selected(feature, resolution) {
172                 if (feature.getGeometry() instanceof ol.geom.Point) return style_point_function_selected(feature, resolution);
173                 return style_path_function(feature, resolution);
174         };
175
176
177         // popup overlay
178         // -------------
179         var popup_container = document.getElementById('popup');
180         var popup_content = document.getElementById('popup-content');
181         var popup_closer = document.getElementById('popup-closer');
182         var popup_overlay = new ol.Overlay({element: popup_container, autoPan: true, autoPanAnimation: {duration: 250}});
183         popup_closer.onclick = function() {popup_overlay.setPosition(undefined); popup_closer.blur(); return false;};
184
185         /*
186         var layer_path = new OpenLayers.Layer.Vector("Path", {
187                 styleMap: new OpenLayers.StyleMap(new OpenLayers.Style({
188                                 strokeColor: '${getStrokeColor}',
189                                 strokeWidth: '${getStrokeWidth}'
190                         }, {
191                                 context: {
192                                         getStrokeColor: function(feature) {
193                                                 if (feature.attributes.strokeColor !== undefined) return feature.attributes.strokeColor;
194                                                 if (feature.attributes.type == 'rodelbahn') return '#014e9a';
195                                                 if (feature.attributes.type == 'gehweg') return '#e98401';
196                                                 if (feature.attributes.type == 'alternative') return '#7f7fff';
197                                                 if (feature.attributes.type == 'lift') return '#000000';
198                                                 if (feature.attributes.type == 'anfahrt') return '#e1e100';
199                                                 return '#e7525b';
200                                         },
201                                         getStrokeWidth: function(feature) {
202                                                 if (feature.attributes.strokeWidth !== undefined) return feature.attributes.strokeWidth;
203                                                 if (feature.attributes.type == 'lift' || feature.attributes.type == 'anfahrt') return 3;
204                                                 return 6;
205                                         }
206                                 }
207                         }))
208         });
209
210         
211         // point layer
212         // -----------
213         var filter_point_sledrun = new OpenLayers.Filter.Comparison({
214                 type: OpenLayers.Filter.Comparison.EQUAL_TO,
215                 property: 'type',
216                 value: 'sledrun'
217         });
218
219
220         var layer_point = new OpenLayers.Layer.Vector("Point", {
221                 styleMap: new OpenLayers.StyleMap({
222                         'default': new OpenLayers.Style({
223                                         graphicZIndex: 12,
224                                         backgroundGraphicZIndex: 11,
225                                 }, {
226                                         context: {
227                                                 // the following context functions should only be available in the rule that uses them,
228                                                 // but the rule dependent contexts are ignored by OpenLayers (I think that's a bug)
229                                                 getCondition: get_sledrun_condition,
230                                                 getSymbol: function(feature) {
231                                                         var name = feature.attributes.type;
232                                                         return name;
233                                                 }
234                                         },
235                                         rules: [
236                                                 new OpenLayers.Rule({
237                                                         filter: filter_point_sledrun,
238                                                         symbolizer: {
239                                                                 externalGraphic: img_path + '/marker_c_sledrun_${getCondition}nn.png',
240                                                                 graphicWidth: 17,
241                                                                 graphicHeight: 17,
242                                                                 graphicXOffset: -8,
243                                                                 graphicYOffset: -8,
244                                                                 backgroundGraphic: img_path + '/marker_c_shadow.png',
245                                                                 backgroundWidth: 23,
246                                                                 backgroundHeight: 23,
247                                                                 backgroundXOffset: -8,
248                                                                 backgroundYOffset: -8,
249                                                         }
250                                                 }),
251                                                 new OpenLayers.Rule({
252                                                         elseFilter: true,
253                                                         symbolizer: {
254                                                                 externalGraphic: img_path + '/marker_p_${getSymbol}.png',
255                                                                 graphicWidth: 20,
256                                                                 graphicHeight: 34,
257                                                                 graphicXOffset: -10,
258                                                                 graphicYOffset: -33,
259                                                         }
260                                                 })
261                                         ]
262                                 }),
263                         highlight: new OpenLayers.Style({
264                                         label: "${getTitle}",
265                                         labelOutlineColor: "white",
266                                         fontWeight: "bold"
267                                 }, {
268                                         context: {
269                                                 getCondition: get_sledrun_condition,
270                                                 getTitle: function(feature) {
271                                                         var title = '';
272                                                         if (feature.attributes.type != 'point') {
273                                                                 title = feature.attributes.type;
274                                                                 title = title.charAt(0).toUpperCase() + title.slice(1); // First letter uppercase
275                                                                 if (feature.attributes.name !== undefined) title += ': ';
276                                                         }
277                                                         if (feature.attributes.name !== undefined) title += feature.attributes.name;
278                                                         return title;
279                                                 }
280                                         },
281                                         rules: [
282                                                 new OpenLayers.Rule({
283                                                         filter: filter_point_sledrun,
284                                                         symbolizer: {
285                                                                 label: "${name}",
286                                                                 labelYOffset: 14,
287                                                                 externalGraphic: img_path + '/marker_c_sledrun_${getCondition}nh.png'
288                                                         }
289                                                 }),
290                                                 new OpenLayers.Rule({
291                                                         elseFilter: true,
292                                                         symbolizer: {
293                                                                 labelYOffset: 40
294                                                         }
295                                                 })
296                                         ]
297                                 }),
298                         select: new OpenLayers.Style({
299                                         fillOpacity: 1.
300                                 }, {
301                                         context: {
302                                                 getCondition: get_sledrun_condition,
303                                         },
304                                         rules: [
305                                                 new OpenLayers.Rule({
306                                                         filter: filter_point_sledrun,
307                                                         symbolizer: {
308                                                                 externalGraphic: img_path + '/marker_c_sledrun_${getCondition}nh.png',
309                                                                 backgroundGraphic: false,
310                                                                 graphicXOffset: -6,
311                                                                 graphicYOffset: -6
312                                                         }
313                                                 }),
314                                                 new OpenLayers.Rule({
315                                                         elseFilter: true
316                                                 })
317                                         ]
318                                 })
319                 }),
320                 rendererOptions: {yOrdering: true}
321         });
322
323 */
324         // map itself
325         // ----------
326         var lon = json_js.properties.lon;
327         var lat = json_js.properties.lat;
328         var zoom = json_js.properties.zoom;
329         var width = json_js.properties.width;
330         var height = json_js.properties.height;
331         if (zoom === undefined) zoom = 10; // default zoom
332         if (width === undefined) width = '100%'; // default width
333         if (height === undefined) height = 450;  // default: 450 pixel
334         jq_map.width(width);
335         jq_map.height(height);
336         /*
337         var map = new OpenLayers.Map(jq_map[0], {
338                 projection: EPSG3857,
339                 displayProjection: EPSG4326,
340                 units: "m",
341                 theme: null,
342                 layers: [layer_map, layer_path, layer_point],
343                 center: new OpenLayers.LonLat(lon, lat).transform(EPSG4326, EPSG3857),
344                 zoom: zoom
345         });
346         */
347
348         var layer_sledrun_source = new ol.source.Vector({features: features_all});
349         var layer_sledrun = new ol.layer.Vector({
350                 source: layer_sledrun_source,
351                 style: style_function
352         });
353
354         var map = new ol.Map({
355                 target: jq_map[0],
356                 layers: [
357                         layer_map,
358                         layer_sledrun
359                 ],
360                 overlays: [popup_overlay],
361                 view: new ol.View({
362                         center: ol.proj.fromLonLat([lon, lat]),
363                         zoom: zoom
364                 }),
365                 controls: ol.control.defaults({
366                         attributionOptions: {
367                                 collapsible: false
368                         }
369                 }),
370                 interactions: ol.interaction.defaults({
371                         mouseWheelZoom: false
372                 })
373         });
374
375
376         var select_hover = new ol.interaction.Select({
377                 condition: ol.events.condition.pointerMove,
378                 style: style_function_selected,
379         });
380         map.addInteraction(select_hover);
381
382         var select_click = new ol.interaction.Select({
383                 condition: ol.events.condition.click,
384         });
385         map.addInteraction(select_click);
386         select_click.on('select', function(event) {
387                 if (event.selected.length > 0) {
388                         let feature = event.selected[0];
389                         let coordinates = feature.getGeometry().getCoordinates();
390                         popup_content.innerHTML = '<p>You clicked</p>';
391                         popup_overlay.setPosition(coordinates);
392                 }
393         });
394
395         /*
396         // add features
397         // if this would be done before the layer is added to the map, the features are not added
398         layer_path.addFeatures(features_path); 
399         layer_point.addFeatures(features_point); 
400
401         // disable mouse wheel zoom
402         var navigation_control = map.getControlsByClass('OpenLayers.Control.Navigation')[0];
403         navigation_control.disableZoomWheel();
404
405         // layer switcher
406         // map.addControl(new OpenLayers.Control.LayerSwitcher());
407
408         // print sledrun name when mouse moves over it
409         map.addControl(new OpenLayers.Control.SelectFeature(layer_point, {
410                 hover: true,
411                 highlightOnly: true,
412                 autoActivate: true,
413                 renderIntent: "highlight"
414         }));
415
416         // show popup when user clicks on a sledrun icon
417         map.addControl(new OpenLayers.Control.SelectFeature(layer_point, {
418                 autoActivate: true,
419                 toggle: true,
420                 onSelect: function(feature) {
421                         var attr = feature.attributes;
422                         var popup_div = createElement('div');
423
424                         // name
425                         if (attr.name !== undefined && (attr.wiki !== undefined || attr.thumb_url !== undefined)) {
426                                 var h2 = appendElement(popup_div, 'h2');
427                                 if (attr.wiki === undefined) h2.text(attr.name);
428                                 else appendElement(h2, 'a', {href: attr.wiki}).text(attr.name);
429                         }
430
431                         // sledrun information
432                         if (attr.type == 'sledrun') {
433                                 var p = appendElement(popup_div, 'p').text('Rodelbahnzustand').append(createElement('br'));
434                                 if (attr.condition !== undefined) {
435                                         var condition_text = {1: 'Sehr gut', 2: 'Gut', 3: 'Mittelmäßig', 4: 'Schlecht', 5: 'Geht nicht'};
436                                         var year_month_day = attr.date_report.split('-');
437                                         p.append(createElement('a', {href: attr.wiki + '#Eintr.C3.A4ge'}).text(condition_text[attr.condition]), ' ');
438                                         p.append(createElement('small').text(year_month_day[2] + '.' + year_month_day[1] + '.'), ' ');
439                                         p.append(createElement('em').append(createElement('a', {href: attr.wiki + '#Eintragen'}).text('Neu')));
440                                 } else {
441                                         p.append(createElement('em').append(createElement('a', {href: attr.wiki + '#Eintragen'}).text('Bitte eintragen')));
442                                 }
443                         }
444
445                         // wiki link
446                         if (attr.wiki !== undefined) {
447                                 var a = appendElement(appendElement(popup_div, 'p'), 'a', {href: attr.wiki});
448                                 var detail_text = 'Details';
449                                 if (attr.type == 'sledrun') detail_text += ' zur Rodelbahn';
450                                 if (attr.type == 'gasthaus') detail_text += ' zum Gasthaus';
451                                 if (attr.thumb_url === undefined) a.text(detail_text);
452                                 else a.append(createElement('img', {src: attr.thumb_url, alt: detail_text, title: detail_text}));
453                         }
454
455                         // no popup if we don't have anything to say
456                         if (popup_div.children().length == 0) return;
457
458                         // Open popup
459                         var selectFeatureControl = this;
460                         var popup = new OpenLayers.Popup.WrInfo('sledruninfopopup_' + attr.wiki,
461                         feature.geometry.getBounds().getCenterLonLat(),
462                         null,
463                         popup_div.html(),
464                         null, true, function(event) {
465                                 // onPopupClose
466                                 selectFeatureControl.unselectAll();
467                         });
468                         feature.popup = popup;
469                         map.addPopup(popup);
470                 },
471                 onUnselect: function(feature) {
472                         if (feature.popup === null) return;
473
474                         // Close popup
475                         map.removePopup(feature.popup);
476                         feature.popup.destroy();
477                         feature.popup = null;
478                 }
479         }));
480 */
481 }
482
483 function init_wrmaps() {
484         var jq_maps = $('.wrmap'); // all wrmap <div> elements
485         jq_maps.each(init_wrmap);
486 }
487
488
489 $(document).ready(init_wrmaps);
490