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