024cc42622b39234847e3944cee7577ebac5cf33
[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 function init_wrmap(i, jq_map) {
17         // define constants
18         var EPSG4326 = new OpenLayers.Projection("EPSG:4326"); // lon/lat
19         var EPSG3857 = new OpenLayers.Projection("EPSG:3857"); // google
20
21         // tool functions
22         function createElement(tagName, attributes) {
23                 var element = $(document.createElement(tagName));
24                 if (attributes === undefined) return element;
25                 for (var attribute in attributes) {
26                         element.attr(attribute, attributes[attribute]);
27                 }
28                 return element;
29         }
30
31         function appendElement(parentElement, tagName, attributes) {
32                 if (attributes === undefined) attributes = {};
33                 var element = createElement(tagName, attributes);
34                 parentElement.append(element);
35                 return element;
36         }
37
38
39         // extract geojson from map element and clear map element's content
40         jq_map = $(jq_map);
41         var ext_path = jq_map.attr('data-ext-path'); // e.g. '/mediawiki/extensions/wrmap'
42         var img_path = ext_path + '/img';
43         OpenLayers.ImgPath = ext_path + '/openlayers/img/'; // e.g. '/mediawiki/extensions/wrmap/openlayers/img/'
44         var json_string = jq_map.children().last().text();
45         jq_map.empty(); // once parsed, remove geojson string from the map element.
46         var format_json = new OpenLayers.Format.JSON();
47         var json_js = format_json.read(json_string);
48         var format_geojson = new OpenLayers.Format.GeoJSON();
49         var features_all = format_geojson.read(json_js);
50
51         // extract, tranform and split features to layers
52         var features_path = new Array();
53         var features_point = new Array();
54         for (var i = 0; i != features_all.length; ++i) {
55                 var feature = features_all[i];
56                 feature.geometry.transform(EPSG4326, EPSG3857);
57                 if (feature.geometry instanceof OpenLayers.Geometry.Point) features_point.push(feature);
58                 else features_path.push(feature);
59         }
60
61
62         // background layer
63         // ----------------
64         // // Google (since about 19th of November 2015 this doesn't work anymore - white background)
65         // var layer_map = new OpenLayers.Layer.Google("Google Physical", {
66         //      type: google.maps.MapTypeId.TERRAIN
67         // });
68
69         // // Alternative: OSM map
70         // var layer_map = new OpenLayers.Layer.OSM();
71         
72         // Microsoft Bing Maps
73         var layer_map = new OpenLayers.Layer.Bing({
74                 type: "Road",
75                 key: "AgPH3SlIXAwajrJKf0FORQyhTqsP8KIlvtN6RKfvxe6fOB6q6-HFmg8EOFm7LSOA"});
76
77         // // Alternative: Base map
78         // // see: http://www.basemap.at
79         
80         // // Alternative: OpenTopoMap
81         // // see: https://opentopomap.org/about
82
83         // // Alternative: Dummy base layer
84         // var layer_map = new OpenLayers.Layer.Vector("Base Layer", {
85         //     isBaseLayer: true});
86
87         
88         // path layer
89         // ----------
90         var layer_path = new OpenLayers.Layer.Vector("Path", {
91                 styleMap: new OpenLayers.StyleMap(new OpenLayers.Style({
92                                 strokeColor: '${getStrokeColor}',
93                                 strokeWidth: '${getStrokeWidth}'
94                         }, {
95                                 context: {
96                                         getStrokeColor: function(feature) {
97                                                 if (feature.attributes.strokeColor !== undefined) return feature.attributes.strokeColor;
98                                                 if (feature.attributes.type == 'rodelbahn') return '#014e9a';
99                                                 if (feature.attributes.type == 'gehweg') return '#e98401';
100                                                 if (feature.attributes.type == 'alternative') return '#7f7fff';
101                                                 if (feature.attributes.type == 'lift') return '#000000';
102                                                 if (feature.attributes.type == 'anfahrt') return '#e1e100';
103                                                 return '#e7525b';
104                                         },
105                                         getStrokeWidth: function(feature) {
106                                                 if (feature.attributes.strokeWidth !== undefined) return feature.attributes.strokeWidth;
107                                                 if (feature.attributes.type == 'lift' || feature.attributes.type == 'anfahrt') return 3;
108                                                 return 6;
109                                         }
110                                 }
111                         }))
112         });
113
114         
115         // point layer
116         // -----------
117         var filter_point_sledrun = new OpenLayers.Filter.Comparison({
118                 type: OpenLayers.Filter.Comparison.EQUAL_TO,
119                 property: 'type',
120                 value: 'sledrun'
121         });
122
123         // Returns 0 to 5 for features that represent sledruns as their condition
124         var get_sledrun_condition = function(feature) {
125                 if (feature.attributes.condition === undefined) return 0;
126                 return feature.attributes.condition;
127         }
128
129
130         var layer_point = new OpenLayers.Layer.Vector("Point", {
131                 styleMap: new OpenLayers.StyleMap({
132                         'default': new OpenLayers.Style({
133                                         graphicZIndex: 12,
134                                         backgroundGraphicZIndex: 11,
135                                 }, {
136                                         context: {
137                                                 // the following context functions should only be available in the rule that uses them,
138                                                 // but the rule dependent contexts are ignored by OpenLayers (I think that's a bug)
139                                                 getCondition: get_sledrun_condition,
140                                                 getSymbol: function(feature) {
141                                                         var name = feature.attributes.type;
142                                                         return name;
143                                                 }
144                                         },
145                                         rules: [
146                                                 new OpenLayers.Rule({
147                                                         filter: filter_point_sledrun,
148                                                         symbolizer: {
149                                                                 externalGraphic: img_path + '/marker_c_sledrun_${getCondition}nn.png',
150                                                                 graphicWidth: 17,
151                                                                 graphicHeight: 17,
152                                                                 graphicXOffset: -8,
153                                                                 graphicYOffset: -8,
154                                                                 backgroundGraphic: img_path + '/marker_c_shadow.png',
155                                                                 backgroundWidth: 23,
156                                                                 backgroundHeight: 23,
157                                                                 backgroundXOffset: -8,
158                                                                 backgroundYOffset: -8,
159                                                         }
160                                                 }),
161                                                 new OpenLayers.Rule({
162                                                         elseFilter: true,
163                                                         symbolizer: {
164                                                                 externalGraphic: img_path + '/marker_p_${getSymbol}.png',
165                                                                 graphicWidth: 20,
166                                                                 graphicHeight: 34,
167                                                                 graphicXOffset: -10,
168                                                                 graphicYOffset: -33,
169                                                         }
170                                                 })
171                                         ]
172                                 }),
173                         highlight: new OpenLayers.Style({
174                                         label: "${getTitle}",
175                                         labelOutlineColor: "white",
176                                         fontWeight: "bold"
177                                 }, {
178                                         context: {
179                                                 getCondition: get_sledrun_condition,
180                                                 getTitle: function(feature) {
181                                                         var title = '';
182                                                         if (feature.attributes.type != 'point') {
183                                                                 title = feature.attributes.type;
184                                                                 title = title.charAt(0).toUpperCase() + title.slice(1); // First letter uppercase
185                                                                 if (feature.attributes.name !== undefined) title += ': ';
186                                                         }
187                                                         if (feature.attributes.name !== undefined) title += feature.attributes.name;
188                                                         return title;
189                                                 }
190                                         },
191                                         rules: [
192                                                 new OpenLayers.Rule({
193                                                         filter: filter_point_sledrun,
194                                                         symbolizer: {
195                                                                 label: "${name}",
196                                                                 labelYOffset: 14,
197                                                                 externalGraphic: img_path + '/marker_c_sledrun_${getCondition}nh.png'
198                                                         }
199                                                 }),
200                                                 new OpenLayers.Rule({
201                                                         elseFilter: true,
202                                                         symbolizer: {
203                                                                 labelYOffset: 40
204                                                         }
205                                                 })
206                                         ]
207                                 }),
208                         select: new OpenLayers.Style({
209                                         fillOpacity: 1.
210                                 }, {
211                                         context: {
212                                                 getCondition: get_sledrun_condition,
213                                         },
214                                         rules: [
215                                                 new OpenLayers.Rule({
216                                                         filter: filter_point_sledrun,
217                                                         symbolizer: {
218                                                                 externalGraphic: img_path + '/marker_c_sledrun_${getCondition}nh.png',
219                                                                 backgroundGraphic: false,
220                                                                 graphicXOffset: -6,
221                                                                 graphicYOffset: -6
222                                                         }
223                                                 }),
224                                                 new OpenLayers.Rule({
225                                                         elseFilter: true
226                                                 })
227                                         ]
228                                 })
229                 }),
230                 rendererOptions: {yOrdering: true}
231         });
232
233
234         // map itself
235         // ----------
236         var lon = json_js.properties.lon;
237         var lat = json_js.properties.lat;
238         var zoom = json_js.properties.zoom;
239         var width = json_js.properties.width;
240         var height = json_js.properties.height;
241         if (zoom === undefined) zoom = 10; // default zoom
242         if (width === undefined) width = '100%'; // default width
243         if (height === undefined) height = 450;  // default: 450 pixel
244         jq_map.width(width);
245         jq_map.height(height);
246         var map = new OpenLayers.Map(jq_map.context, {
247                 projection: EPSG3857,
248                 displayProjection: EPSG4326,
249                 units: "m",
250                 theme: null,
251                 layers: [layer_map, layer_path, layer_point],
252                 center: new OpenLayers.LonLat(lon, lat).transform(EPSG4326, EPSG3857),
253                 zoom: zoom
254         });
255         
256
257         // add features
258         // if this would be done before the layer is added to the map, the features are not added
259         layer_path.addFeatures(features_path); 
260         layer_point.addFeatures(features_point); 
261
262         // disable mouse wheel zoom
263         var navigation_control = map.getControlsByClass('OpenLayers.Control.Navigation')[0];
264         navigation_control.disableZoomWheel();
265
266         // layer switcher
267         // map.addControl(new OpenLayers.Control.LayerSwitcher());
268
269         // print sledrun name when mouse moves over it
270         map.addControl(new OpenLayers.Control.SelectFeature(layer_point, {
271                 hover: true,
272                 highlightOnly: true,
273                 autoActivate: true,
274                 renderIntent: "highlight"
275         }));
276
277         // show popup when user clicks on a sledrun icon
278         map.addControl(new OpenLayers.Control.SelectFeature(layer_point, {
279                 autoActivate: true,
280                 toggle: true,
281                 onSelect: function(feature) {
282                         var attr = feature.attributes;
283                         var popup_div = createElement('div');
284
285                         // name
286                         if (attr.name !== undefined && (attr.wiki !== undefined || attr.thumb_url !== undefined)) {
287                                 var h2 = appendElement(popup_div, 'h2');
288                                 if (attr.wiki === undefined) h2.text(attr.name);
289                                 else appendElement(h2, 'a', {href: attr.wiki}).text(attr.name);
290                         }
291
292                         // sledrun information
293                         if (attr.type == 'sledrun') {
294                                 var p = appendElement(popup_div, 'p').text('Rodelbahnzustand').append(createElement('br'));
295                                 if (attr.condition !== undefined) {
296                                         var condition_text = {1: 'Sehr gut', 2: 'Gut', 3: 'Mittelmäßig', 4: 'Schlecht', 5: 'Geht nicht'};
297                                         var year_month_day = attr.date_report.split('-');
298                                         p.append(createElement('a', {href: attr.wiki + '#Eintr.C3.A4ge'}).text(condition_text[attr.condition]), ' ');
299                                         p.append(createElement('small').text(year_month_day[2] + '.' + year_month_day[1] + '.'), ' ');
300                                         p.append(createElement('em').append(createElement('a', {href: attr.wiki + '#Eintragen'}).text('Neu')));
301                                 } else {
302                                         p.append(createElement('em').append(createElement('a', {href: attr.wiki + '#Eintragen'}).text('Bitte eintragen')));
303                                 }
304                         }
305
306                         // wiki link
307                         if (attr.wiki !== undefined) {
308                                 var a = appendElement(appendElement(popup_div, 'p'), 'a', {href: attr.wiki});
309                                 var detail_text = 'Details';
310                                 if (attr.type == 'sledrun') detail_text += ' zur Rodelbahn';
311                                 if (attr.type == 'gasthaus') detail_text += ' zum Gasthaus';
312                                 if (attr.thumb_url === undefined) a.text(detail_text);
313                                 else a.append(createElement('img', {src: attr.thumb_url, alt: detail_text, title: detail_text}));
314                         }
315
316                         // no popup if we don't have anything to say
317                         if (popup_div.children().length == 0) return;
318
319                         // Open popup
320                         var selectFeatureControl = this;
321                         var popup = new OpenLayers.Popup.WrInfo('sledruninfopopup_' + attr.wiki,
322                         feature.geometry.getBounds().getCenterLonLat(),
323                         null,
324                         popup_div.html(),
325                         null, true, function(event) {
326                                 // onPopupClose
327                                 selectFeatureControl.unselectAll();
328                         });
329                         feature.popup = popup;
330                         map.addPopup(popup);
331                 },
332                 onUnselect: function(feature) {
333                         if (feature.popup === null) return;
334
335                         // Close popup
336                         map.removePopup(feature.popup);
337                         feature.popup.destroy();
338                         feature.popup = null;
339                 }
340         }));
341 }
342
343
344 function init_wrmaps() {
345         var jq_maps = $('.wrmap'); // all wrmap <div> elements
346         jq_maps.each(init_wrmap);
347 }
348
349
350 $(document).ready(init_wrmaps);
351