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