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