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