]> dev.renevier.net Git - syp.git/blob - js/syp.js
multi user administration
[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     Markers: {
21         ICON: "media/marker-normal.png",
22         SELECT_ICON: "media/marker-selected.png",
23         HEIGHT: 25
24     },
25
26     map: null,
27     baseLayer: null,
28     dataLayer: null,
29     selectControl: null,
30
31     init: function() {
32         this.map = new OpenLayers.Map("map", {
33             controls:[
34                 new OpenLayers.Control.SypAttribution(),
35                 new OpenLayers.Control.Navigation(),
36                 new OpenLayers.Control.PanZoom(),
37                 new OpenLayers.Control.Permalink()
38             ],
39             projection: new OpenLayers.Projection("EPSG:900913"),
40             displayProjection: new OpenLayers.Projection("EPSG:4326")
41         } );
42
43         this.baseLayer = this.createBaseLayer();
44         this.dataLayer = this.createDataLayer();
45         this.map.addLayers([this.baseLayer, this.dataLayer]);
46
47         this.selectControl = this.createSelectControl();
48         this.map.addControl(this.selectControl);
49         this.selectControl.activate();
50
51         if (!this.map.getCenter()) {
52             this.map.setCenter(new OpenLayers.LonLat(0, 0), 0);
53         }
54     },
55
56     createBaseLayer: function() {
57         return new OpenLayers.Layer.OSM("OSM");
58     },
59
60     createDataLayer: function(map) {
61         var defaultStyle = new OpenLayers.Style({
62             externalGraphic: this.Markers.ICON,
63             graphicHeight: "${height}"
64         }, {
65             context: {
66                 height: function(feature) {
67                     var defaultHeight = SYP.Markers.HEIGHT || 32;
68                     var increase = 4 * (feature.attributes.count - 1);
69                     return Math.min(defaultHeight + increase, 50);
70                 }
71             }
72         });
73         var selectStyle = new OpenLayers.Style({
74             externalGraphic: this.Markers.SELECT_ICON,
75             graphicHeight: this.Markers.HEIGHT || 32 
76         });
77         var styleMap = new OpenLayers.StyleMap (
78                         {"default": defaultStyle,
79                          "select": selectStyle});
80
81         var layer = new OpenLayers.Layer.GML("KML", "items.php", 
82            {
83                strategies: [
84                 new OpenLayers.Strategy.Cluster()
85                 ],
86             styleMap: styleMap,
87             format: OpenLayers.Format.KML, 
88             projection: this.map.displayProjection,
89             eventListeners: { scope: this,
90                               loadend: this.dataLayerEndLoad
91                             }
92            });
93
94         return layer;
95     },
96
97     createSelectControl: function() {
98         var control = new OpenLayers.Control.SelectFeature(
99                                             this.dataLayer, {
100                                                onSelect: this.onFeatureSelect,
101                                                onUnselect: this.onFeatureUnselect,
102                                                toggle: true,
103                                                clickout: false
104                                                             });
105         return control;
106     },
107
108     dataLayerEndLoad: function() {
109         if (!this.checkForFeatures()) {
110             return;
111         }
112
113         var map = this.map;
114         if (map.getControlsByClass("OpenLayers.Control.ArgParser")[0].lat
115             == undefined) { // map center was not set in ArgParser control.
116             var orig = this.Utils.mbr (this.dataLayer);
117             var centerBounds = new OpenLayers.Bounds();
118
119             var mapProj = map.getProjectionObject();
120             var sypOrigProj = new OpenLayers.Projection("EPSG:4326");
121
122             var bottomLeft = new OpenLayers.LonLat(orig[0],orig[1]);
123             bottomLeft = bottomLeft.transform(sypOrigProj, mapProj);
124             var topRight = new OpenLayers.LonLat(orig[2],orig[3])
125             topRight = topRight.transform(sypOrigProj, mapProj);
126
127             centerBounds.extend(bottomLeft);
128             centerBounds.extend(topRight);
129             map.zoomToExtent(centerBounds);
130         }
131     },
132
133     checkForFeatures: function() {
134         var features = this.dataLayer.features;
135         if (features.length == 0) {
136             var message = SypStrings.noImageRegistered;
137             this.Utils.displayUserMessage(message, "warn");
138         }
139         return !!features.length;
140     },
141
142     createPopup: function(position, contentHTML) {
143         var popup = new OpenLayers.Popup.Anchored("popup",
144                                                   position,
145                                                   null,
146                                                   contentHTML,
147                                                   null,
148                                                   true);
149         popup.autoSize = true;
150         popup.backgroundColor = ""; // deal with it in css
151         popup.border = ""; // deal with it in css
152         popup.closeOnMove = true;
153         return popup;
154     },
155
156     onFeatureUnselect: function (feature) {
157         var map = feature.layer.map;
158         var permaControl = map.getControlsByClass("OpenLayers.Control.Permalink");
159         if (permaControl[0]) {
160             permaControl[0].div.style.display = "";
161         }
162         if (!feature.popup) {
163             this.map.events.unregister("movestart", this, this._unselect);
164             return;
165         }
166         var popup = feature.popup;
167         if (popup.visible()) {
168             popup.hide();
169         }
170     },
171
172     onFeatureSelect: function(feature) {
173         var map = feature.layer.map;
174         if (feature.attributes.count > 1) {
175             this.unselect(feature);
176             var lonlat = new OpenLayers.LonLat(feature.geometry.x, feature.geometry.y);
177             map.setCenter(lonlat, map.zoom + 1);
178             return;
179         }
180         var permaControl = map.getControlsByClass("OpenLayers.Control.Permalink");
181         if (permaControl[0]) {
182             permaControl[0].div.style.display = "none";
183         }
184         var popup = feature.popup;
185
186         var popupPos = null;
187         if (sypSettings.popupNearfeature) {
188             popupPos = feature.geometry.getBounds().getCenterLonLat();
189         } else {
190             popupPos = SYP.Utils.brCorner(map, 8);
191         }
192
193         // we cannot reuse popup; we need to recreate it in order for IE
194         // expressions to work. Otherwise, we get a 0x0 image on second view.
195         if (popup) {
196             popup.destroy();
197         }
198         var contentHTML;
199         if (feature.cluster[0].attributes.name) {
200             contentHTML = "<h2>" +
201                           feature.cluster[0].attributes.name + 
202                           "</h2>" + 
203                           feature.cluster[0].attributes.description;
204         } else {
205             contentHTML = feature.cluster[0].attributes.description;
206         }
207         if (!contentHTML || !contentHTML.length) {
208             this.map.events.register("movestart", this, this._unselect = function () { this.unselect(feature)});
209             return;
210         }
211         popup = SYP.createPopup(popupPos, contentHTML);
212         var control = this;
213         popup.hide = function () {
214             OpenLayers.Element.hide(this.div);
215             control.unselectAll();
216         };
217         map.addPopup(popup);
218         feature.popup = popup;
219         var anchor = popup.div.getElementsByTagName("a")[0];
220         if (anchor) {
221             anchor.onclick = function() { 
222                 SYP.showBigImage(this.href);
223                 return false;
224             }
225         }
226     },
227
228     showBigImage: function (href) {
229         try {
230             document.getElementById('bigimg_container').style.display = "table";
231         } catch(e) {
232             document.getElementById('bigimg_container').style.display = "block";
233         }
234         var maxHeight = document.body.clientHeight * 0.9;
235         var maxWidth = document.body.clientWidth * 0.9;
236         document.getElementById('bigimg').style.height = "";
237         document.getElementById('bigimg').style.width = "";
238         document.getElementById('bigimg').style.maxHeight = maxHeight + "px";
239         document.getElementById('bigimg').style.maxWidth = maxWidth + "px";
240         document.getElementById('bigimg').onload = function () {
241             var icon = document.getElementById('bigimg_close');
242             icon.style.top = this.offsetTop;
243             icon.style.left = this.offsetLeft + this.clientWidth - icon.clientWidth;
244
245             var heightRatio = this.clientHeight / parseInt(this.style.maxHeight);
246             var widthRatio = this.clientWidth / parseInt(this.style.maxWidth);
247             if (heightRatio > 1 || widthRatio > 1) {
248                 if (heightRatio > widthRatio) {
249                     this.style.height = this.style.maxHeight;
250                 } else {
251                     this.style.width = this.style.maxWidth;
252                 }
253             }
254
255         };
256         document.getElementById('bigimg').src = href;
257     },
258
259     closeBigImage: function() {
260         document.getElementById('bigimg').src = "";
261         document.getElementById('bigimg').parentNode.innerHTML = document.getElementById('bigimg').parentNode.innerHTML;
262         document.getElementById('bigimg_container').style.display = "none";
263     },
264
265     Utils: {
266         brCorner: function(map, margin) {
267             var bounds = map.calculateBounds();
268             var corner = new OpenLayers.LonLat(bounds.right, bounds.bottom);
269             var cornerAsPx = map.getPixelFromLonLat(corner);
270             cornerAsPx = cornerAsPx.add( -margin, -margin);
271             corner = map.getLonLatFromPixel(cornerAsPx);
272             return corner;
273         },
274
275         /* minimum bounds rectangle containing all feature locations.
276          * FIXME: if two features are close, but separated by 180th meridian,
277          * their mbr will span the whole earth. Actually, 179° lon and -170°
278          * lon are considerated very near.
279          */
280         mbr: function (layer) {
281             var features = [];
282             var map = layer.map;
283
284             var mapProj = map.getProjectionObject();
285             var sypOrigProj = new OpenLayers.Projection("EPSG:4326");
286
287             for (var i =0; i < layer.features.length; i++) {
288                 if (layer.features[i].cluster) {
289                     features = features.concat(layer.features[i].cluster);
290                 } else {
291                     features = features.concat(layer.features);
292                 }
293             }
294
295             var minlon = 180;
296             var minlat = 88;
297             var maxlon = -180;
298             var maxlat = -88;
299
300             if (features.length == 0) {
301                 // keep default values
302             } else if (features.length == 1) {
303                 // in case there's only one feature, we show an area of at least 
304                 // 4 x 4 degrees
305                 var pos = features[0].geometry.getBounds().getCenterLonLat().clone();
306                 var lonlat = pos.transform(mapProj, sypOrigProj);
307
308                 minlon = Math.max (lonlat.lon - 2, -180);
309                 maxlon = Math.min (lonlat.lon + 2, 180);
310                 minlat = Math.max (lonlat.lat - 2, -90);
311                 maxlat = Math.min (lonlat.lat + 2, 90);
312             } else {
313                 for (var i = 0; i < features.length; i++) {
314                     var pos = features[i].geometry.getBounds().getCenterLonLat().clone();
315                     var lonlat = pos.transform(mapProj, sypOrigProj);
316                     minlon = Math.min (lonlat.lon, minlon);
317                     minlat = Math.min (lonlat.lat, minlat);
318                     maxlon = Math.max (lonlat.lon, maxlon);
319                     maxlat = Math.max (lonlat.lat, maxlat);
320                 }
321             }
322
323             return [minlon, minlat, maxlon, maxlat];
324
325         },
326
327         displayUserMessage: function(message, status) {
328             var div = document.getElementById('message');
329             while (div.firstChild)
330                 div.removeChild(div.firstChild);
331             var textNode = document.createTextNode(message);
332             switch (status) {
333                 case "error":
334                     div.style.color = "red";
335                     break;
336                 case "warn":
337                     div.style.color = "#FF8C00";
338                     break;
339                 case "success":
340                     div.style.color = "green";
341                     break;
342                 default:
343                     div.style.color = "black";
344                     break;
345             }
346             div.style.display = "block";
347             div.appendChild(textNode);
348         }
349     }
350 };
351
352 // if possible, determine language with HTTP_ACCEPT_LANGUAGE instead of
353 // navigator.language
354 if (OpenLayers.Lang[SypStrings.language]) {
355     OpenLayers.Lang.setCode(SypStrings.language);
356 }
357
358 // avoid alerts
359 OpenLayers.Console.userError = function(error) { 
360     SYP.Utils.displayUserMessage(error, "error");
361 }
362
363 // sometimes, especially when cache is clear, firefox does not compute
364 // correctly popup size. That's because at the end of getRenderedDimensions,
365 // dimensions of image is not known. So, we work around that problem by setting
366 // image width and image height. That way, dimensions of image are set in
367 // innerHTML, and are therefore known in getRenderedDimensions
368 OpenLayers.Popup.Anchored.prototype.registerImageListeners = function() {
369     var onImgLoad = function() {
370         this.img.width =  this.img.width;
371         this.img.height =  this.img.height;
372         this.popup.updateSize();
373         OpenLayers.Event.stopObserving(
374             this.img, "load", this.img._onImageLoad
375         );
376     };
377
378     var images = this.contentDiv.getElementsByTagName("img");
379     for (var i = 0, len = images.length; i < len; i++) {
380         var img = images[i];
381         if (img.width == 0 || img.height == 0) {
382
383             var context = {
384                 'popup': this,
385                 'img': img
386             };
387
388             img._onImgLoad = OpenLayers.Function.bind(onImgLoad, context);
389
390             OpenLayers.Event.observe(img, 'load', img._onImgLoad);
391         }    
392     } 
393 }