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