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