]> dev.renevier.net Git - syp.git/blob - js/syp.js
d8a54b5d5a59611d44cb4663e5dbec309161abb7
[syp.git] / js / syp.js
1 /* Copyright (c) 2009 Arnaud Renevier, Inc, published under the modified BSD
2  * license. */
3
4 OpenLayers.Control.SypAttribution = OpenLayers.Class (OpenLayers.Control.Attribution, {
5     updateAttribution: function() {
6         var attributions = [SypStrings.propulsedByLink];
7         if (this.map && this.map.layers) {
8             for(var i=0, len=this.map.layers.length; i<len; i++) {
9                 var layer = this.map.layers[i];
10                 if (layer.attribution && layer.getVisibility()) {
11                     attributions.push( layer.attribution );
12                 }
13             }  
14             this.div.innerHTML = attributions.join(this.separator);
15         }
16     }
17 });
18
19 var SYP = {
20     Settings: {
21         MARKER_ICON: "openlayers/img/marker-blue.png",
22         MARKER_ICON_HEIGHT: 25,
23         MARKER_SELECT_ICON: "openlayers/img/marker-green.png",
24         MARKER_SELECT_ICON_HEIGHT: 25
25     },
26
27     map: null,
28     baseLayer: null,
29     dataLayer: null,
30     selectControl: null,
31
32     init: function() {
33         this.map = new OpenLayers.Map("map", {
34             controls:[
35                 new OpenLayers.Control.SypAttribution(),
36                 new OpenLayers.Control.Navigation(),
37                 new OpenLayers.Control.PanZoom(),
38                 new OpenLayers.Control.Permalink()
39             ],
40             projection: new OpenLayers.Projection("EPSG:900913"),
41             displayProjection: new OpenLayers.Projection("EPSG:4326")
42         } );
43
44         this.baseLayer = this.createBaseLayer();
45         this.dataLayer = this.createDataLayer();
46         this.map.addLayers([this.baseLayer, this.dataLayer]);
47
48         this.selectControl = this.createSelectControl();
49         this.map.addControl(this.selectControl);
50         this.selectControl.activate();
51
52         if (!this.map.getCenter()) {
53             var centerBounds = new OpenLayers.Bounds();
54
55             var mapProj = this.map.getProjectionObject();
56             var sypOrigProj = new OpenLayers.Projection("EPSG:4326");
57
58             var bottomLeft = new OpenLayers.LonLat(sypOrig[0],sypOrig[1]);
59             bottomLeft = bottomLeft.transform(sypOrigProj, mapProj);
60             var topRight = new OpenLayers.LonLat(sypOrig[2],sypOrig[3])
61             topRight = topRight.transform(sypOrigProj, mapProj);
62
63             centerBounds.extend(bottomLeft);
64             centerBounds.extend(topRight);
65             this.map.zoomToExtent(centerBounds);
66         }
67     },
68
69     createBaseLayer: function() {
70         return new OpenLayers.Layer.OSM("OSM");
71     },
72
73     createDataLayer: function(map) {
74         var defaultStyle = new OpenLayers.Style({
75             externalGraphic: this.Settings.MARKER_ICON,
76             graphicHeight: "${height}"
77         }, {
78             context: {
79                 height: function(feature) {
80                     var defaultHeight = SYP.Settings.MARKER_ICON_HEIGHT || 32;
81                     var increase = 4 * (feature.attributes.count - 1);
82                     return Math.min(defaultHeight + increase, 50);
83                 }
84             }
85         });
86         var selectStyle = new OpenLayers.Style({
87             externalGraphic: this.Settings.MARKER_SELECT_ICON,
88             graphicHeight: this.Settings.MARKER_SELECT_ICON_HEIGHT || 32 
89         });
90         var styleMap = new OpenLayers.StyleMap (
91                         {"default": defaultStyle,
92                          "select": selectStyle});
93
94         var layer = new OpenLayers.Layer.GML("KML", "items.php", 
95            {
96                strategies: [
97                 new OpenLayers.Strategy.Cluster()
98                 ],
99             styleMap: styleMap,
100             format: OpenLayers.Format.KML, 
101             projection: this.map.displayProjection,
102             eventListeners: { scope: this,
103                               loadend: this.checkForFeatures
104                             }
105            });
106
107         return layer;
108     },
109
110     createSelectControl: function() {
111         var control = new OpenLayers.Control.SelectFeature(
112                                             this.dataLayer, {
113                                                onSelect: this.onFeatureSelect,
114                                                onUnselect: this.onFeatureUnselect,
115                                                toggle: true,
116                                                clickout: false
117                                                             });
118         return control;
119     },
120
121     checkForFeatures: function() {
122         var features = this.dataLayer.features;
123         if (features.length == 0) {
124             var message = SypStrings.noImageRegistered;
125             this.Utils.displayUserMessage(message, "warn");
126         }
127     },
128
129     createPopup: function(position, contentHTML) {
130         var popup = new OpenLayers.Popup.Anchored("popup",
131                                                   position,
132                                                   null,
133                                                   contentHTML,
134                                                   null,
135                                                   true);
136         popup.autoSize = true;
137         popup.backgroundColor = ""; // deal with it in css
138         popup.border = ""; // deal with it in css
139         popup.closeOnMove = true;
140         return popup;
141     },
142
143     onFeatureUnselect: function (feature) {
144         var map = feature.layer.map;
145         var permaControl = map.getControlsByClass("OpenLayers.Control.Permalink");
146         if (permaControl[0]) {
147             permaControl[0].div.style.display = "";
148         }
149         if (!feature.popup) {
150             this.map.events.unregister("movestart", this, this._unselect);
151             return;
152         }
153         var popup = feature.popup;
154         if (popup.visible()) {
155             popup.hide();
156         }
157     },
158
159     onFeatureSelect: function(feature) {
160         var map = feature.layer.map;
161         if (feature.attributes.count > 1) {
162             this.unselect(feature);
163             var lonlat = new OpenLayers.LonLat(feature.geometry.x, feature.geometry.y);
164             map.setCenter(lonlat, map.zoom + 1);
165             return;
166         }
167         var permaControl = map.getControlsByClass("OpenLayers.Control.Permalink");
168         if (permaControl[0]) {
169             permaControl[0].div.style.display = "none";
170         }
171         var popup = feature.popup;
172
173         var brCorner = SYP.Utils.brCorner(map, 8);
174
175         // we cannot reuse popup; we need to recreate it in order for IE
176         // expressions to work. Otherwise, we get a 0x0 image on second view.
177         if (popup) {
178             popup.destroy();
179         }
180         var contentHTML;
181         if (feature.cluster[0].attributes.name) {
182             contentHTML = "<h2>" +
183                           feature.cluster[0].attributes.name + 
184                           "</h2>" + 
185                           feature.cluster[0].attributes.description;
186         } else {
187             contentHTML = feature.cluster[0].attributes.description;
188         }
189         if (!contentHTML || !contentHTML.length) {
190             this.map.events.register("movestart", this, this._unselect = function () { this.unselect(feature)});
191             return;
192         }
193         popup = SYP.createPopup(brCorner, contentHTML);
194         var control = this;
195         popup.hide = function () {
196             OpenLayers.Element.hide(this.div);
197             control.unselectAll();
198         };
199         map.addPopup(popup);
200         feature.popup = popup;
201         var anchor = popup.div.getElementsByTagName("a")[0];
202         if (anchor) {
203             anchor.onclick = function() { 
204                 SYP.showBigImage(this.href);
205                 return false;
206             }
207         }
208     },
209
210     showBigImage: function (href) {
211         try {
212             document.getElementById('bigimg_container').style.display = "table";
213         } catch(e) {
214             document.getElementById('bigimg_container').style.display = "block";
215         }
216         var maxHeight = document.body.clientHeight * 0.9;
217         var maxWidth = document.body.clientWidth * 0.9;
218         document.getElementById('bigimg').style.height = "";
219         document.getElementById('bigimg').style.width = "";
220         document.getElementById('bigimg').style.maxHeight = maxHeight + "px";
221         document.getElementById('bigimg').style.maxWidth = maxWidth + "px";
222         document.getElementById('bigimg').onload = function () {
223             var icon = document.getElementById('bigimg_close');
224             icon.style.top = this.offsetTop;
225             icon.style.left = this.offsetLeft + this.clientWidth - icon.clientWidth;
226
227             var heightRatio = this.clientHeight / parseInt(this.style.maxHeight);
228             var widthRatio = this.clientWidth / parseInt(this.style.maxWidth);
229             if (heightRatio > 1 || widthRatio > 1) {
230                 if (heightRatio > widthRatio) {
231                     this.style.height = this.style.maxHeight;
232                 } else {
233                     this.style.width = this.style.maxWidth;
234                 }
235             }
236
237         };
238         document.getElementById('bigimg').src = href;
239     },
240
241     closeBigImage: function() {
242         document.getElementById('bigimg').src = "";
243         document.getElementById('bigimg').parentNode.innerHTML = document.getElementById('bigimg').parentNode.innerHTML;
244         document.getElementById('bigimg_container').style.display = "none";
245     },
246
247     Utils: {
248         brCorner: function(map, margin) {
249             var bounds = map.calculateBounds();
250             var corner = new OpenLayers.LonLat(bounds.right, bounds.bottom);
251             var cornerAsPx = map.getPixelFromLonLat(corner);
252             cornerAsPx = cornerAsPx.add( -margin, -margin);
253             corner = map.getLonLatFromPixel(cornerAsPx);
254             return corner;
255         },
256         displayUserMessage: function(message, status) {
257             var div = document.getElementById('message');
258             while (div.firstChild)
259                 div.removeChild(div.firstChild);
260             var textNode = document.createTextNode(message);
261             switch (status) {
262                 case "error":
263                     div.style.color = "red";
264                     break;
265                 case "warn":
266                     div.style.color = "#FF8C00";
267                     break;
268                 case "success":
269                     div.style.color = "green";
270                     break;
271                 default:
272                     div.style.color = "black";
273                     break;
274             }
275             div.style.display = "block";
276             div.appendChild(textNode);
277         }
278     }
279 };
280
281 // if possible, determine language with HTTP_ACCEPT_LANGUAGE instead of
282 // navigator.language
283 if (OpenLayers.Lang[SypStrings.language]) {
284     OpenLayers.Lang.setCode(SypStrings.language);
285 }
286
287 // avoid alerts
288 OpenLayers.Console.userError = function(error) { 
289     SYP.Utils.displayUserMessage(error, "error");
290 }
291
292 // sometimes, especially when cache is clear, firefox does not compute
293 // correctly popup size. That's because at the end of getRenderedDimensions,
294 // dimensions of image is not known. So, we work around that problem by setting
295 // image width and image height. That way, dimensions of image are set in
296 // innerHTML, and are therefore known in getRenderedDimensions
297 OpenLayers.Popup.Anchored.prototype.registerImageListeners = function() {
298     var onImgLoad = function() {
299         this.img.width =  this.img.width;
300         this.img.height =  this.img.height;
301         this.popup.updateSize();
302         OpenLayers.Event.stopObserving(
303             this.img, "load", this.img._onImageLoad
304         );
305     };
306
307     var images = this.contentDiv.getElementsByTagName("img");
308     for (var i = 0, len = images.length; i < len; i++) {
309         var img = images[i];
310         if (img.width == 0 || img.height == 0) {
311
312             var context = {
313                 'popup': this,
314                 'img': img
315             };
316
317             img._onImgLoad = OpenLayers.Function.bind(onImgLoad, context);
318
319             OpenLayers.Event.observe(img, 'load', img._onImgLoad);
320         }    
321     } 
322 }