ae02ab2b1385cd91819cad8b81a0e65aa2301bb0
[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                                                                 backgroundGraphic: false,
198                                                                 graphicXOffset: -6,
199                                                                 graphicYOffset: -6
200                                                         }
201                                                 }),
202                                                 new OpenLayers.Rule({
203                                                         elseFilter: true
204                                                 })
205                                         ]
206                                 })
207                 }),
208                 rendererOptions: {yOrdering: true}
209         });
210
211
212         // map itself
213         // ----------
214         var lon = json_js.properties.lon;
215         var lat = json_js.properties.lat;
216         var zoom = json_js.properties.zoom;
217         var width = json_js.properties.width;
218         var height = json_js.properties.height;
219         if (zoom === undefined) zoom = 10; // default zoom
220         if (width === undefined) width = '100%'; // default width
221         if (height === undefined) height = 450;  // default: 450 pixel
222         jq_map.width(width);
223         jq_map.height(height);
224         var map = new OpenLayers.Map(jq_map.context, {
225                 projection: EPSG3857,
226                 displayProjection: EPSG4326,
227                 units: "m",
228                 theme: null,
229                 layers: [layer_map, layer_path, layer_point],
230                 center: new OpenLayers.LonLat(lon, lat).transform(EPSG4326, EPSG3857),
231                 zoom: zoom
232         });
233         
234
235         // add features
236         // if this would be done before the layer is added to the map, the features are not added
237         layer_path.addFeatures(features_path); 
238         layer_point.addFeatures(features_point); 
239
240         // disable mouse wheel zoom
241         var navigation_control = map.getControlsByClass('OpenLayers.Control.Navigation')[0];
242         navigation_control.disableZoomWheel();
243
244         // layer switcher
245         // map.addControl(new OpenLayers.Control.LayerSwitcher());
246
247         // print sledrun name when mouse moves over it
248         map.addControl(new OpenLayers.Control.SelectFeature(layer_point, {
249                 hover: true,
250                 highlightOnly: true,
251                 autoActivate: true,
252                 renderIntent: "highlight"
253         }));
254
255         // show popup when user clicks on a sledrun icon
256         map.addControl(new OpenLayers.Control.SelectFeature(layer_point, {
257                 autoActivate: true,
258                 toggle: true,
259                 onSelect: function(feature) {
260                         var attr = feature.attributes;
261                         var popup_div = createElement('div');
262
263                         // name
264                         if (attr.name !== undefined && (attr.wiki !== undefined || attr.thumb_url !== undefined)) {
265                                 var h2 = appendElement(popup_div, 'h2');
266                                 if (attr.wiki === undefined) h2.text(attr.name);
267                                 else appendElement(h2, 'a', {href: attr.wiki}).text(attr.name);
268                         }
269
270                         // sledrun information
271                         if (attr.type == 'sledrun') {
272                                 var p = appendElement(popup_div, 'p').text('Rodelbahnzustand').append(createElement('br'));
273                                 if (attr.condition !== undefined) {
274                                         var condition_text = {1: 'Sehr gut', 2: 'Gut', 3: 'Mittelmäßig', 4: 'Schlecht', 5: 'Geht nicht'};
275                                         var year_month_day = attr.date_report.split('-');
276                                         p.append(createElement('a', {href: attr.wiki + '#Eintr.C3.A4ge'}).text(condition_text[attr.condition]), ' ');
277                                         p.append(createElement('small').text(year_month_day[2] + '.' + year_month_day[1] + '.'), ' ');
278                                         p.append(createElement('em').append(createElement('a', {href: attr.wiki + '#Eintragen'}).text('Neu')));
279                                 } else {
280                                         p.append(createElement('em').append(createElement('a', {href: attr.wiki + '#Eintragen'}).text('Bitte eintragen')));
281                                 }
282                         }
283
284                         // wiki link
285                         if (attr.wiki !== undefined) {
286                                 var a = appendElement(appendElement(popup_div, 'p'), 'a', {href: attr.wiki});
287                                 var detail_text = 'Details';
288                                 if (attr.type == 'sledrun') detail_text += ' zur Rodelbahn';
289                                 if (attr.type == 'gasthaus') detail_text += ' zum Gasthaus';
290                                 if (attr.thumb_url === undefined) a.text(detail_text);
291                                 else a.append(createElement('img', {src: attr.thumb_url, alt: detail_text, title: detail_text}));
292                         }
293
294                         // no popup if we don't have anything to say
295                         if (popup_div.children().length == 0) return;
296
297                         // Open popup
298                         var selectFeatureControl = this;
299                         var popup = new OpenLayers.Popup.FramedCloud('sledruninfopopup_' + attr.wiki,
300                         feature.geometry.getBounds().getCenterLonLat(),
301                         null,
302                         popup_div.html(),
303                         null, true, function(event) {
304                                 // onPopupClose
305                                 selectFeatureControl.unselectAll();
306                         });
307                         feature.popup = popup;
308                         map.addPopup(popup);
309                 },
310                 onUnselect: function(feature) {
311                         if (feature.popup === null) return;
312
313                         // Close popup
314                         map.removePopup(feature.popup);
315                         feature.popup.destroy();
316                         feature.popup = null;
317                 }
318         }));
319 }
320
321
322 function init_wrmaps() {
323         var jq_maps = $('.wrmap'); // all wrmap <div> elements
324         jq_maps.each(init_wrmap);
325 }
326
327
328 $(document).ready(init_wrmaps);
329