8b7607b943123c0b98518a889fa846938ca27550
[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                 title = title.charAt(0).toUpperCase() + title.slice(1); // first letter uppercase
99                 if (feature.get('name')) title += ': ' + feature.get('name');
100                 return title;
101         }
102
103         function style_point_function(feature, resolution) {
104                 var src = img_path + '/marker_p_' + feature.get('type') + '.png';
105                 return new ol.style.Style({
106                         image: new ol.style.Icon({
107                                 src: src,
108                                 imgSize: [20, 34],
109                                 anchor: [0.5, 1.0]
110                         }),
111                 });
112         }
113
114         function style_point_function_selected(feature, resolution) {
115                 var style = style_point_function(feature, resolution);
116                 style.setText(new ol.style.Text({
117                         text: get_feature_title(feature),
118                         font: 'icon',
119                         offsetY: 14,
120                         stroke: new ol.style.Stroke({
121                                 color: '#ddd',
122                                 width: 2,
123                         }),
124                 }));
125                 return style;
126         }
127
128         function style_path_function(feature, resolution) {
129                 var line_color = {
130                         'rodelbahn': '#014e9a',
131                         'gehweg': '#e98401',
132                         'alternative': '#7f7fff',
133                         'lift': '#000000',
134                         'anfahrt': '#e1e100'
135                 };
136                 var color = feature.get('strokeColor') || line_color[feature.get('type')] || '#e7525b';
137                 var width = (feature.get('type') in ['lift', 'anfahrt']) ? 3 : 6;
138                 return new ol.style.Style({
139                         stroke: new ol.style.Stroke({
140                                 color: color,
141                                 width: width
142                         })
143                 });
144         }
145
146         function style_function(feature, resolution) {
147                 if (feature.getGeometry() instanceof ol.geom.Point) return style_point_function(feature, resolution);
148                 return style_path_function(feature, resolution);
149         };
150
151         function style_function_selected(feature, resolution) {
152                 if (feature.getGeometry() instanceof ol.geom.Point) return style_point_function_selected(feature, resolution);
153                 return style_path_function(feature, resolution);
154         };
155
156         // popup overlay
157         // -------------
158         var popup_container = document.getElementById('popup');
159         var popup_content = document.getElementById('popup-content');
160         var popup_closer = document.getElementById('popup-closer');
161         var popup_overlay = new ol.Overlay({element: popup_container, autoPan: true, autoPanAnimation: {duration: 250}});
162         popup_closer.onclick = function() {popup_overlay.setPosition(undefined); popup_closer.blur(); return false;};
163
164         /*
165         var layer_path = new OpenLayers.Layer.Vector("Path", {
166                 styleMap: new OpenLayers.StyleMap(new OpenLayers.Style({
167                                 strokeColor: '${getStrokeColor}',
168                                 strokeWidth: '${getStrokeWidth}'
169                         }, {
170                                 context: {
171                                         getStrokeColor: function(feature) {
172                                                 if (feature.attributes.strokeColor !== undefined) return feature.attributes.strokeColor;
173                                                 if (feature.attributes.type == 'rodelbahn') return '#014e9a';
174                                                 if (feature.attributes.type == 'gehweg') return '#e98401';
175                                                 if (feature.attributes.type == 'alternative') return '#7f7fff';
176                                                 if (feature.attributes.type == 'lift') return '#000000';
177                                                 if (feature.attributes.type == 'anfahrt') return '#e1e100';
178                                                 return '#e7525b';
179                                         },
180                                         getStrokeWidth: function(feature) {
181                                                 if (feature.attributes.strokeWidth !== undefined) return feature.attributes.strokeWidth;
182                                                 if (feature.attributes.type == 'lift' || feature.attributes.type == 'anfahrt') return 3;
183                                                 return 6;
184                                         }
185                                 }
186                         }))
187         });
188
189         
190         // point layer
191         // -----------
192         var filter_point_sledrun = new OpenLayers.Filter.Comparison({
193                 type: OpenLayers.Filter.Comparison.EQUAL_TO,
194                 property: 'type',
195                 value: 'sledrun'
196         });
197
198         // Returns 0 to 5 for features that represent sledruns as their condition
199         var get_sledrun_condition = function(feature) {
200                 if (feature.attributes.condition === undefined) return 0;
201                 return feature.attributes.condition;
202         }
203
204
205         var layer_point = new OpenLayers.Layer.Vector("Point", {
206                 styleMap: new OpenLayers.StyleMap({
207                         'default': new OpenLayers.Style({
208                                         graphicZIndex: 12,
209                                         backgroundGraphicZIndex: 11,
210                                 }, {
211                                         context: {
212                                                 // the following context functions should only be available in the rule that uses them,
213                                                 // but the rule dependent contexts are ignored by OpenLayers (I think that's a bug)
214                                                 getCondition: get_sledrun_condition,
215                                                 getSymbol: function(feature) {
216                                                         var name = feature.attributes.type;
217                                                         return name;
218                                                 }
219                                         },
220                                         rules: [
221                                                 new OpenLayers.Rule({
222                                                         filter: filter_point_sledrun,
223                                                         symbolizer: {
224                                                                 externalGraphic: img_path + '/marker_c_sledrun_${getCondition}nn.png',
225                                                                 graphicWidth: 17,
226                                                                 graphicHeight: 17,
227                                                                 graphicXOffset: -8,
228                                                                 graphicYOffset: -8,
229                                                                 backgroundGraphic: img_path + '/marker_c_shadow.png',
230                                                                 backgroundWidth: 23,
231                                                                 backgroundHeight: 23,
232                                                                 backgroundXOffset: -8,
233                                                                 backgroundYOffset: -8,
234                                                         }
235                                                 }),
236                                                 new OpenLayers.Rule({
237                                                         elseFilter: true,
238                                                         symbolizer: {
239                                                                 externalGraphic: img_path + '/marker_p_${getSymbol}.png',
240                                                                 graphicWidth: 20,
241                                                                 graphicHeight: 34,
242                                                                 graphicXOffset: -10,
243                                                                 graphicYOffset: -33,
244                                                         }
245                                                 })
246                                         ]
247                                 }),
248                         highlight: new OpenLayers.Style({
249                                         label: "${getTitle}",
250                                         labelOutlineColor: "white",
251                                         fontWeight: "bold"
252                                 }, {
253                                         context: {
254                                                 getCondition: get_sledrun_condition,
255                                                 getTitle: function(feature) {
256                                                         var title = '';
257                                                         if (feature.attributes.type != 'point') {
258                                                                 title = feature.attributes.type;
259                                                                 title = title.charAt(0).toUpperCase() + title.slice(1); // First letter uppercase
260                                                                 if (feature.attributes.name !== undefined) title += ': ';
261                                                         }
262                                                         if (feature.attributes.name !== undefined) title += feature.attributes.name;
263                                                         return title;
264                                                 }
265                                         },
266                                         rules: [
267                                                 new OpenLayers.Rule({
268                                                         filter: filter_point_sledrun,
269                                                         symbolizer: {
270                                                                 label: "${name}",
271                                                                 labelYOffset: 14,
272                                                                 externalGraphic: img_path + '/marker_c_sledrun_${getCondition}nh.png'
273                                                         }
274                                                 }),
275                                                 new OpenLayers.Rule({
276                                                         elseFilter: true,
277                                                         symbolizer: {
278                                                                 labelYOffset: 40
279                                                         }
280                                                 })
281                                         ]
282                                 }),
283                         select: new OpenLayers.Style({
284                                         fillOpacity: 1.
285                                 }, {
286                                         context: {
287                                                 getCondition: get_sledrun_condition,
288                                         },
289                                         rules: [
290                                                 new OpenLayers.Rule({
291                                                         filter: filter_point_sledrun,
292                                                         symbolizer: {
293                                                                 externalGraphic: img_path + '/marker_c_sledrun_${getCondition}nh.png',
294                                                                 backgroundGraphic: false,
295                                                                 graphicXOffset: -6,
296                                                                 graphicYOffset: -6
297                                                         }
298                                                 }),
299                                                 new OpenLayers.Rule({
300                                                         elseFilter: true
301                                                 })
302                                         ]
303                                 })
304                 }),
305                 rendererOptions: {yOrdering: true}
306         });
307
308 */
309         // map itself
310         // ----------
311         var lon = json_js.properties.lon;
312         var lat = json_js.properties.lat;
313         var zoom = json_js.properties.zoom;
314         var width = json_js.properties.width;
315         var height = json_js.properties.height;
316         if (zoom === undefined) zoom = 10; // default zoom
317         if (width === undefined) width = '100%'; // default width
318         if (height === undefined) height = 450;  // default: 450 pixel
319         jq_map.width(width);
320         jq_map.height(height);
321         /*
322         var map = new OpenLayers.Map(jq_map.context, {
323                 projection: EPSG3857,
324                 displayProjection: EPSG4326,
325                 units: "m",
326                 theme: null,
327                 layers: [layer_map, layer_path, layer_point],
328                 center: new OpenLayers.LonLat(lon, lat).transform(EPSG4326, EPSG3857),
329                 zoom: zoom
330         });
331         */
332
333         var layer_sledrun_source = new ol.source.Vector({features: features_all});
334         var layer_sledrun = new ol.layer.Vector({
335                 source: layer_sledrun_source,
336                 style: style_function
337         });
338
339         var map = new ol.Map({
340                 target: jq_map.context,
341                 layers: [
342                         layer_map,
343                         layer_sledrun
344                 ],
345                 overlays: [popup_overlay],
346                 view: new ol.View({
347                         center: ol.proj.fromLonLat([lon, lat]),
348                         zoom: zoom
349                 }),
350                 controls: ol.control.defaults({
351                         attributionOptions: {
352                                 collapsible: false
353                         }
354                 })
355         });
356
357
358         var select_hover = new ol.interaction.Select({
359                 condition: ol.events.condition.pointerMove,
360                 style: style_function_selected,
361         });
362         map.addInteraction(select_hover);
363         map.on('singleclick', function(event) {
364                 popup_content.innerHTML = '<p>You clicked</p>';
365                 popup_overlay.setPosition(event.coordinate);
366         });
367         select_hover.on('select', function(event) {
368                 console.log(event);
369         });
370
371         /*
372         // add features
373         // if this would be done before the layer is added to the map, the features are not added
374         layer_path.addFeatures(features_path); 
375         layer_point.addFeatures(features_point); 
376
377         // disable mouse wheel zoom
378         var navigation_control = map.getControlsByClass('OpenLayers.Control.Navigation')[0];
379         navigation_control.disableZoomWheel();
380
381         // layer switcher
382         // map.addControl(new OpenLayers.Control.LayerSwitcher());
383
384         // print sledrun name when mouse moves over it
385         map.addControl(new OpenLayers.Control.SelectFeature(layer_point, {
386                 hover: true,
387                 highlightOnly: true,
388                 autoActivate: true,
389                 renderIntent: "highlight"
390         }));
391
392         // show popup when user clicks on a sledrun icon
393         map.addControl(new OpenLayers.Control.SelectFeature(layer_point, {
394                 autoActivate: true,
395                 toggle: true,
396                 onSelect: function(feature) {
397                         var attr = feature.attributes;
398                         var popup_div = createElement('div');
399
400                         // name
401                         if (attr.name !== undefined && (attr.wiki !== undefined || attr.thumb_url !== undefined)) {
402                                 var h2 = appendElement(popup_div, 'h2');
403                                 if (attr.wiki === undefined) h2.text(attr.name);
404                                 else appendElement(h2, 'a', {href: attr.wiki}).text(attr.name);
405                         }
406
407                         // sledrun information
408                         if (attr.type == 'sledrun') {
409                                 var p = appendElement(popup_div, 'p').text('Rodelbahnzustand').append(createElement('br'));
410                                 if (attr.condition !== undefined) {
411                                         var condition_text = {1: 'Sehr gut', 2: 'Gut', 3: 'Mittelmäßig', 4: 'Schlecht', 5: 'Geht nicht'};
412                                         var year_month_day = attr.date_report.split('-');
413                                         p.append(createElement('a', {href: attr.wiki + '#Eintr.C3.A4ge'}).text(condition_text[attr.condition]), ' ');
414                                         p.append(createElement('small').text(year_month_day[2] + '.' + year_month_day[1] + '.'), ' ');
415                                         p.append(createElement('em').append(createElement('a', {href: attr.wiki + '#Eintragen'}).text('Neu')));
416                                 } else {
417                                         p.append(createElement('em').append(createElement('a', {href: attr.wiki + '#Eintragen'}).text('Bitte eintragen')));
418                                 }
419                         }
420
421                         // wiki link
422                         if (attr.wiki !== undefined) {
423                                 var a = appendElement(appendElement(popup_div, 'p'), 'a', {href: attr.wiki});
424                                 var detail_text = 'Details';
425                                 if (attr.type == 'sledrun') detail_text += ' zur Rodelbahn';
426                                 if (attr.type == 'gasthaus') detail_text += ' zum Gasthaus';
427                                 if (attr.thumb_url === undefined) a.text(detail_text);
428                                 else a.append(createElement('img', {src: attr.thumb_url, alt: detail_text, title: detail_text}));
429                         }
430
431                         // no popup if we don't have anything to say
432                         if (popup_div.children().length == 0) return;
433
434                         // Open popup
435                         var selectFeatureControl = this;
436                         var popup = new OpenLayers.Popup.WrInfo('sledruninfopopup_' + attr.wiki,
437                         feature.geometry.getBounds().getCenterLonLat(),
438                         null,
439                         popup_div.html(),
440                         null, true, function(event) {
441                                 // onPopupClose
442                                 selectFeatureControl.unselectAll();
443                         });
444                         feature.popup = popup;
445                         map.addPopup(popup);
446                 },
447                 onUnselect: function(feature) {
448                         if (feature.popup === null) return;
449
450                         // Close popup
451                         map.removePopup(feature.popup);
452                         feature.popup.destroy();
453                         feature.popup = null;
454                 }
455         }));
456 */
457 }
458
459 function init_wrmaps() {
460         var jq_maps = $('.wrmap'); // all wrmap <div> elements
461         jq_maps.each(init_wrmap);
462 }
463
464
465 $(document).ready(init_wrmaps);
466