]> dev.renevier.net Git - syp.git/blob - js/syp.js
uses cluster strategy for items presentation
[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     },
202
203     Utils: {
204         brCorner: function(map, margin) {
205             var bounds = map.calculateBounds();
206             var corner = new OpenLayers.LonLat(bounds.right, bounds.bottom);
207             var cornerAsPx = map.getPixelFromLonLat(corner);
208             cornerAsPx = cornerAsPx.add( -margin, -margin);
209             corner = map.getLonLatFromPixel(cornerAsPx);
210             return corner;
211         },
212         displayUserMessage: function(message, status) {
213             var div = document.getElementById('message');
214             while (div.firstChild)
215                 div.removeChild(div.firstChild);
216             var textNode = document.createTextNode(message);
217             switch (status) {
218                 case "error":
219                     div.style.color = "red";
220                     break;
221                 case "warn":
222                     div.style.color = "#FF8C00";
223                     break;
224                 case "success":
225                     div.style.color = "green";
226                     break;
227                 default:
228                     div.style.color = "black";
229                     break;
230             }
231             div.style.display = "block";
232             div.appendChild(textNode);
233         }
234     }
235 };
236
237 // if possible, determine language with HTTP_ACCEPT_LANGUAGE instead of
238 // navigator.language
239 if (OpenLayers.Lang[SypStrings.language]) {
240     OpenLayers.Lang.setCode(SypStrings.language);
241 }
242
243 // avoid alerts
244 OpenLayers.Console.userError = function(error) { 
245     SYP.Utils.displayUserMessage(error, "error");
246 }
247
248 // sometimes, especially when cache is clear, firefox does not compute
249 // correctly popup size. That's because at the end of getRenderedDimensions,
250 // dimensions of image is not known. So, we work around that problem by setting
251 // image width and image height. That way, dimensions of image are set in
252 // innerHTML, and are therefore known in getRenderedDimensions
253 OpenLayers.Popup.Anchored.prototype.registerImageListeners = function() {
254     var onImgLoad = function() {
255         this.img.width =  this.img.width;
256         this.img.height =  this.img.height;
257         this.popup.updateSize();
258         OpenLayers.Event.stopObserving(
259             this.img, "load", this.img._onImageLoad
260         );
261     };
262
263     var images = this.contentDiv.getElementsByTagName("img");
264     for (var i = 0, len = images.length; i < len; i++) {
265         var img = images[i];
266         if (img.width == 0 || img.height == 0) {
267
268             var context = {
269                 'popup': this,
270                 'img': img
271             };
272
273             img._onImgLoad = OpenLayers.Function.bind(onImgLoad, context);
274
275             OpenLayers.Event.observe(img, 'load', img._onImgLoad);
276         }    
277     } 
278 }