]> dev.renevier.net Git - syp.git/blob - js/syp.js
do not display attribution
[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         switch (sypSettings.popupPos) {
188             case 0:
189                 popupPos = feature.geometry.getBounds().getCenterLonLat();
190             break;
191             case 1:
192                 popupPos = SYP.Utils.tlCorner(map, 8);
193             break;
194             case 2:
195                 popupPos = SYP.Utils.trCorner(map, 8);
196             break;
197             case 3:
198                 popupPos = SYP.Utils.brCorner(map, 8);
199             break;
200             case 4:
201                 popupPos = SYP.Utils.blCorner(map, 8);
202             break;
203             default:
204                 popupPos = SYP.Utils.brCorner(map, 8);
205            break;
206         }
207
208         // we cannot reuse popup; we need to recreate it in order for IE
209         // expressions to work. Otherwise, we get a 0x0 image on second view.
210         if (popup) {
211             popup.destroy();
212         }
213         var contentHTML;
214         if (feature.cluster[0].attributes.name) {
215             // escaping name is necessary because it's not enclosed in another html tag.
216             contentHTML = "<h2>" +
217                           SYP.Utils.escapeHTML(feature.cluster[0].attributes.name) +
218                           "</h2>" + 
219                           feature.cluster[0].attributes.description;
220         } else {
221             contentHTML = feature.cluster[0].attributes.description;
222         }
223         if (!contentHTML || !contentHTML.length) {
224             this.map.events.register("movestart", this, this._unselect = function () { this.unselect(feature)});
225             return;
226         }
227         popup = SYP.createPopup(popupPos, contentHTML);
228         var control = this;
229         popup.hide = function () {
230             OpenLayers.Element.hide(this.div);
231             control.unselectAll();
232         };
233         map.addPopup(popup);
234         feature.popup = popup;
235         var anchor = popup.div.getElementsByTagName("a")[0];
236         if (anchor) {
237             anchor.onclick = function() { 
238                 SYP.showBigImage(this.href);
239                 return false;
240             }
241         }
242     },
243
244     showBigImage: function (href) {
245         if (OpenLayers.Util.getBrowserName() == "msie") {
246             document.getElementById('bigimg_container').style.display = "block";
247         } else {
248             document.getElementById('bigimg_container').style.display = "table";
249         }
250
251         var maxHeight = document.body.clientHeight * 0.9;
252         var maxWidth = document.body.clientWidth * 0.9;
253         document.getElementById('bigimg').style.height = "";
254         document.getElementById('bigimg').style.width = "";
255         document.getElementById('bigimg').style.maxHeight = maxHeight + "px";
256         document.getElementById('bigimg').style.maxWidth = maxWidth + "px";
257         document.getElementById('bigimg').onload = function () {
258             var heightRatio = this.clientHeight / parseInt(this.style.maxHeight);
259             var widthRatio = this.clientWidth / parseInt(this.style.maxWidth);
260             if (heightRatio > 1 || widthRatio > 1) {
261                 if (heightRatio > widthRatio) {
262                     this.style.height = this.style.maxHeight;
263                 } else {
264                     this.style.width = this.style.maxWidth;
265                 }
266             }
267
268             var icon = document.getElementById('bigimg_close');
269             icon.style.top = this.offsetTop;
270             icon.style.left = this.offsetLeft + this.clientWidth - icon.clientWidth;
271
272         };
273         document.getElementById('bigimg').src = href;
274     },
275
276     closeBigImage: function() {
277         document.getElementById('bigimg').src = "";
278         document.getElementById('bigimg').parentNode.innerHTML = document.getElementById('bigimg').parentNode.innerHTML;
279         document.getElementById('bigimg_container').style.display = "none";
280     },
281
282     Utils: {
283         tlCorner: function(map, margin) {
284             var bounds = map.calculateBounds();
285             var corner = new OpenLayers.LonLat(bounds.left, bounds.top);
286             var cornerAsPx = map.getPixelFromLonLat(corner);
287             cornerAsPx = cornerAsPx.add( +margin, +margin);
288             return map.getLonLatFromPixel(cornerAsPx);
289         },
290
291         trCorner: function(map, margin) {
292             var bounds = map.calculateBounds();
293             var corner = new OpenLayers.LonLat(bounds.right, bounds.top);
294             var cornerAsPx = map.getPixelFromLonLat(corner);
295             cornerAsPx = cornerAsPx.add( -margin, +margin);
296             return map.getLonLatFromPixel(cornerAsPx);
297         },
298
299         brCorner: function(map, margin) {
300             var bounds = map.calculateBounds();
301             var corner = new OpenLayers.LonLat(bounds.right, bounds.bottom);
302             var cornerAsPx = map.getPixelFromLonLat(corner);
303             cornerAsPx = cornerAsPx.add( -margin, -margin);
304             return map.getLonLatFromPixel(cornerAsPx);
305         },
306
307         blCorner: function(map, margin) {
308             var bounds = map.calculateBounds();
309             var corner = new OpenLayers.LonLat(bounds.left, bounds.bottom);
310             var cornerAsPx = map.getPixelFromLonLat(corner);
311             cornerAsPx = cornerAsPx.add( +margin, -margin);
312             return map.getLonLatFromPixel(cornerAsPx);
313         },
314
315         /* minimum bounds rectangle containing all feature locations.
316          * FIXME: if two features are close, but separated by 180th meridian,
317          * their mbr will span the whole earth. Actually, 179° lon and -170°
318          * lon are considerated very near.
319          */
320         mbr: function (layer) {
321             var features = [];
322             var map = layer.map;
323
324             var mapProj = map.getProjectionObject();
325             var sypOrigProj = new OpenLayers.Projection("EPSG:4326");
326
327             for (var i =0; i < layer.features.length; i++) {
328                 if (layer.features[i].cluster) {
329                     features = features.concat(layer.features[i].cluster);
330                 } else {
331                     features = features.concat(layer.features);
332                 }
333             }
334
335             var minlon = 180;
336             var minlat = 88;
337             var maxlon = -180;
338             var maxlat = -88;
339
340             if (features.length == 0) {
341                 // keep default values
342             } else if (features.length == 1) {
343                 // in case there's only one feature, we show an area of at least 
344                 // 4 x 4 degrees
345                 var pos = features[0].geometry.getBounds().getCenterLonLat().clone();
346                 var lonlat = pos.transform(mapProj, sypOrigProj);
347
348                 minlon = Math.max (lonlat.lon - 2, -180);
349                 maxlon = Math.min (lonlat.lon + 2, 180);
350                 minlat = Math.max (lonlat.lat - 2, -90);
351                 maxlat = Math.min (lonlat.lat + 2, 90);
352             } else {
353                 for (var i = 0; i < features.length; i++) {
354                     var pos = features[i].geometry.getBounds().getCenterLonLat().clone();
355                     var lonlat = pos.transform(mapProj, sypOrigProj);
356                     minlon = Math.min (lonlat.lon, minlon);
357                     minlat = Math.min (lonlat.lat, minlat);
358                     maxlon = Math.max (lonlat.lon, maxlon);
359                     maxlat = Math.max (lonlat.lat, maxlat);
360                 }
361             }
362
363             return [minlon, minlat, maxlon, maxlat];
364
365         },
366
367         displayUserMessage: function(message, status) {
368             var div = document.getElementById('message');
369             while (div.firstChild)
370                 div.removeChild(div.firstChild);
371             var textNode = document.createTextNode(message);
372             switch (status) {
373                 case "error":
374                     div.style.color = "red";
375                     break;
376                 case "warn":
377                     div.style.color = "#FF8C00";
378                     break;
379                 case "success":
380                     div.style.color = "green";
381                     break;
382                 default:
383                     div.style.color = "black";
384                     break;
385             }
386             div.style.display = "block";
387             div.appendChild(textNode);
388         },
389
390         escapeHTML: function (str) {
391             if (!str) {
392                 return "";
393             }
394             return str.
395              replace(/&/gm, '&amp;').
396              replace(/'/gm, '&#39;').
397              replace(/"/gm, '&quot;').
398              replace(/>/gm, '&gt;').
399              replace(/</gm, '&lt;');
400         }
401     }
402 };
403
404 // if possible, determine language with HTTP_ACCEPT_LANGUAGE instead of
405 // navigator.language
406 if (OpenLayers.Lang[SypStrings.language]) {
407     OpenLayers.Lang.setCode(SypStrings.language);
408 }
409
410 // avoid alerts
411 OpenLayers.Console.userError = function(error) { 
412     SYP.Utils.displayUserMessage(error, "error");
413 }
414
415 // sometimes, especially when cache is clear, firefox does not compute
416 // correctly popup size. That's because at the end of getRenderedDimensions,
417 // dimensions of image is not known. Then, popup size is too small for its
418 // content. We work around the problem by checking that computed size is at
419 // least as big as content. To achieve that, we need to override
420 // OpenLayers.Popup.Anchored.prototype.updateSize to modify it slightly.
421 OpenLayers.Popup.Anchored.prototype.updateSize = function() {
422     // determine actual render dimensions of the contents by putting its
423     // contents into a fake contentDiv (for the CSS) and then measuring it
424     var preparedHTML = "<div class='" + this.contentDisplayClass+ "'>" + 
425         this.contentDiv.innerHTML + 
426         "</div>";
427
428     var containerElement = (this.map) ? this.map.layerContainerDiv
429                                       : document.body;
430     var realSize = OpenLayers.Util.getRenderedDimensions(
431         preparedHTML, null,     {
432             displayClass: this.displayClass,
433             containerElement: containerElement
434         }
435     );
436
437     /*
438      * XXX: next four lines are added by SYP!
439      */
440     if (this.contentDiv) {
441         realSize.w = Math.max (realSize.w, this.contentDiv.scrollWidth);
442         realSize.h = Math.max (realSize.h, this.contentDiv.scrollHeight);
443     }
444
445     // is the "real" size of the div is safe to display in our map?
446     var safeSize = this.getSafeContentSize(realSize);
447
448     var newSize = null;
449     if (safeSize.equals(realSize)) {
450         //real size of content is small enough to fit on the map, 
451         // so we use real size.
452         newSize = realSize;
453
454     } else {
455
456         //make a new OL.Size object with the clipped dimensions 
457         // set or null if not clipped.
458         var fixedSize = new OpenLayers.Size();
459         fixedSize.w = (safeSize.w < realSize.w) ? safeSize.w : null;
460         fixedSize.h = (safeSize.h < realSize.h) ? safeSize.h : null;
461
462             if (fixedSize.w && fixedSize.h) {
463                 //content is too big in both directions, so we will use 
464                 // max popup size (safeSize), knowing well that it will 
465                 // overflow both ways.                
466                 newSize = safeSize;
467             } else {
468                 //content is clipped in only one direction, so we need to 
469                 // run getRenderedDimensions() again with a fixed dimension
470                 var clippedSize = OpenLayers.Util.getRenderedDimensions(
471                     preparedHTML, fixedSize, {
472                         displayClass: this.contentDisplayClass,
473                         containerElement: containerElement
474                     }
475                 );
476
477                 //if the clipped size is still the same as the safeSize, 
478                 // that means that our content must be fixed in the 
479                 // offending direction. If overflow is 'auto', this means 
480                 // we are going to have a scrollbar for sure, so we must 
481                 // adjust for that.
482                 //
483                 var currentOverflow = OpenLayers.Element.getStyle(
484                     this.contentDiv, "overflow"
485                 );
486                 if ( (currentOverflow != "hidden") && 
487                      (clippedSize.equals(safeSize)) ) {
488                     var scrollBar = OpenLayers.Util.getScrollbarWidth();
489                     if (fixedSize.w) {
490                         clippedSize.h += scrollBar;
491                     } else {
492                         clippedSize.w += scrollBar;
493                     }
494                 }
495
496                 newSize = this.getSafeContentSize(clippedSize);
497             }
498         }                        
499         this.setSize(newSize);     
500 }