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