1 /* Copyright (c) 2009 Arnaud Renevier, Inc, published under the modified BSD
5 * With canvas rendering engine, externalgraphics are drawn by loading and
6 * Image javascript object and drawing it with drawImage once it has been
7 * loaded. If matching feature is deleted while image is loading, redraw
8 * function will be called before drawImage and therefore, feature is removed,
9 * but image is still drawn on the screen. We fix it with locks: when an image is
10 * loading, we defer redraw method.
12 OpenLayers.Renderer.Canvas.prototype = OpenLayers.Util.extend({
15 }, OpenLayers.Renderer.Canvas.prototype);
16 OpenLayers.Renderer.Canvas.prototype.oldRedraw = OpenLayers.Renderer.Canvas.prototype.redraw;
17 OpenLayers.Renderer.Canvas.prototype.redraw = function() {
18 if (this.imagesLoading > 0) {
19 this.needsRedraw = true;
22 OpenLayers.Renderer.Canvas.prototype.oldRedraw.apply(this, arguments);
24 OpenLayers.Renderer.Canvas.prototype.drawExternalGraphic = function(pt, style) {
25 var img = new Image();
26 img.src = style.externalGraphic;
28 if(style.graphicTitle) {
29 img.title=style.graphicTitle;
32 var width = style.graphicWidth || style.graphicHeight;
33 var height = style.graphicHeight || style.graphicWidth;
34 width = width ? width : style.pointRadius*2;
35 height = height ? height : style.pointRadius*2;
36 var xOffset = (style.graphicXOffset != undefined) ?
37 style.graphicXOffset : -(0.5 * width);
38 var yOffset = (style.graphicYOffset != undefined) ?
39 style.graphicYOffset : -(0.5 * height);
40 var opacity = style.graphicOpacity || style.fillOpacity;
42 var context = { img: img,
47 canvas: this.canvas };
51 img.onerror = function() {
53 if ((self.imagesLoading == 0) && (self.needsRedraw)) {
54 self.needsRedraw = false;
58 img.onload = OpenLayers.Function.bind( function() {
60 if ((self.imagesLoading == 0) && (self.needsRedraw)) {
61 self.needsRedraw = false;
64 this.canvas.drawImage(this.img, this.x,
65 this.y, this.width, this.height);
71 OpenLayers.Control.SypAttribution = OpenLayers.Class (OpenLayers.Control.Attribution, {
72 updateAttribution: function() {
73 var attributions = [SypStrings.poweredByLink];
74 if (this.map && this.map.layers) {
75 for(var i=0, len=this.map.layers.length; i<len; i++) {
76 var layer = this.map.layers[i];
77 if (layer.attribution && layer.getVisibility()) {
78 attributions.push( layer.attribution );
81 this.div.innerHTML = attributions.join(this.separator);
88 ICON: "media/marker-normal.png",
89 SELECT_ICON: "media/marker-selected.png",
99 this.map = new OpenLayers.Map("map", {
101 new OpenLayers.Control.SypAttribution(),
102 new OpenLayers.Control.Navigation(),
103 new OpenLayers.Control.PanZoom(),
104 new OpenLayers.Control.Permalink()
106 projection: new OpenLayers.Projection("EPSG:900913"),
107 displayProjection: new OpenLayers.Projection("EPSG:4326")
110 this.baseLayer = this.createBaseLayer();
111 this.dataLayer = this.createDataLayer();
112 this.map.addLayers([this.baseLayer, this.dataLayer]);
114 this.selectControl = this.createSelectControl();
115 this.map.addControl(this.selectControl);
116 this.selectControl.activate();
118 if (!this.map.getCenter()) {
119 this.map.setCenter(new OpenLayers.LonLat(0, 0), 0);
123 createBaseLayer: function() {
124 return new OpenLayers.Layer.OSM("OSM");
127 createDataLayer: function(map) {
128 var defaultStyle = new OpenLayers.Style({
129 externalGraphic: this.Markers.ICON,
130 graphicHeight: "${height}",
136 height: function(feature) {
137 var defaultHeight = SYP.Markers.HEIGHT || 32;
138 var increase = 4 * (feature.attributes.count - 1);
139 return Math.min(defaultHeight + increase, 50);
141 label: function(feature) {
142 var renderer = feature.layer.renderer;
143 if (renderer.CLASS_NAME == "OpenLayers.Renderer.Canvas") {
144 return ""; // canvas backend cannot draw text above an external Image
146 return (feature.attributes.count > 1) ? feature.attributes.count: "";
150 var selectStyle = new OpenLayers.Style({
151 externalGraphic: this.Markers.SELECT_ICON,
152 graphicHeight: this.Markers.HEIGHT || 32
154 var styleMap = new OpenLayers.StyleMap (
155 {"default": defaultStyle,
156 "select": selectStyle});
158 var layer = new OpenLayers.Layer.GML("KML", "items.php",
161 new OpenLayers.Strategy.Cluster()
164 format: OpenLayers.Format.KML,
165 projection: this.map.displayProjection,
166 eventListeners: { scope: this,
167 loadend: this.dataLayerEndLoad
174 createSelectControl: function() {
175 var control = new OpenLayers.Control.SelectFeature(
177 onSelect: this.onFeatureSelect,
178 onUnselect: this.onFeatureUnselect,
185 dataLayerEndLoad: function() {
186 if (!this.checkForFeatures()) {
191 if (map.getControlsByClass("OpenLayers.Control.ArgParser")[0].center
192 == null) { // map center was not set in ArgParser control.
193 var orig = this.Utils.mbr (this.dataLayer);
194 var centerBounds = new OpenLayers.Bounds();
196 var mapProj = map.getProjectionObject();
197 var sypOrigProj = new OpenLayers.Projection("EPSG:4326");
199 var bottomLeft = new OpenLayers.LonLat(orig[0],orig[1]);
200 bottomLeft = bottomLeft.transform(sypOrigProj, mapProj);
201 var topRight = new OpenLayers.LonLat(orig[2],orig[3])
202 topRight = topRight.transform(sypOrigProj, mapProj);
204 centerBounds.extend(bottomLeft);
205 centerBounds.extend(topRight);
206 map.zoomToExtent(centerBounds);
210 checkForFeatures: function() {
211 var features = this.dataLayer.features;
212 if (features.length == 0) {
213 var message = SypStrings.noImageRegistered;
214 this.Utils.displayUserMessage(message, "warn");
216 return !!features.length;
219 createPopup: function(position, contentHTML) {
220 var popup = new OpenLayers.Popup.Anchored("popup",
226 popup.autoSize = true;
227 popup.backgroundColor = ""; // deal with it in css
228 popup.border = ""; // deal with it in css
229 popup.closeOnMove = true;
233 onFeatureUnselect: function (feature) {
234 var map = feature.layer.map;
235 var permaControl = map.getControlsByClass("OpenLayers.Control.Permalink");
236 if (permaControl[0]) {
237 permaControl[0].div.style.display = "";
239 if (!feature.popup) {
240 this.map.events.unregister("movestart", this, this._unselect);
243 var popup = feature.popup;
244 if (popup.visible()) {
249 onZoomClusterEnd: function(arg) {
250 var map = arg.object;
251 var point = new OpenLayers.Geometry.Point(this.lonlat.lon, this.lonlat.lat);
252 var center = map.getCenter();
253 for (var i = this.layer.features.length; i-->0;) {
254 var feature = this.layer.features[i];
255 if (feature.geometry.equals(point) &&
256 (feature.attributes.count == this.count)) {
258 window.setTimeout(function() { map.setCenter(self.lonlat, map.zoom + 1)}, 500);
262 SYP.selectControl.activate();
263 map.events.unregister("zoomend", this, SYP.onZoomClusterEnd);
266 onFeatureSelect: function(feature) {
267 var map = feature.layer.map;
269 if (feature.attributes.count > 1) {
270 this.unselect(feature);
271 var lonlat = new OpenLayers.LonLat(feature.geometry.x, feature.geometry.y);
274 layer: feature.layer,
275 count: feature.attributes.count
277 map.events.register("zoomend", args, SYP.onZoomClusterEnd);
278 SYP.selectControl.deactivate();
279 map.setCenter(lonlat, map.zoom + 1);
282 var permaControl = map.getControlsByClass("OpenLayers.Control.Permalink");
283 if (permaControl[0]) {
284 permaControl[0].div.style.display = "none";
286 var popup = feature.popup;
289 switch (sypSettings.popupPos) {
291 popupPos = feature.geometry.getBounds().getCenterLonLat();
294 popupPos = SYP.Utils.tlCorner(map, 8);
297 popupPos = SYP.Utils.trCorner(map, 8);
300 popupPos = SYP.Utils.brCorner(map, 8);
303 popupPos = SYP.Utils.blCorner(map, 8);
306 popupPos = SYP.Utils.brCorner(map, 8);
310 // we cannot reuse popup; we need to recreate it in order for IE
311 // expressions to work. Otherwise, we get a 0x0 image on second view.
316 if (feature.cluster[0].attributes.name) {
317 // escaping name is necessary because it's not enclosed in another html tag.
318 contentHTML = "<h2>" +
319 SYP.Utils.escapeHTML(feature.cluster[0].attributes.name) +
321 feature.cluster[0].attributes.description;
323 contentHTML = feature.cluster[0].attributes.description;
325 if (!contentHTML || !contentHTML.length) {
326 this.map.events.register("movestart", this, this._unselect = function () { this.unselect(feature)});
329 popup = SYP.createPopup(popupPos, contentHTML);
331 popup.hide = function () {
332 OpenLayers.Element.hide(this.div);
333 control.unselectAll();
336 feature.popup = popup;
337 var anchor = popup.div.getElementsByTagName("a")[0];
339 anchor.onclick = function() {
340 SYP.showBigImage(this.href);
346 showBigImage: function (href) {
347 if (OpenLayers.Util.getBrowserName() == "msie") {
348 document.getElementById('bigimg_container').style.display = "block";
350 document.getElementById('bigimg_container').style.display = "table";
353 var maxHeight = document.body.clientHeight * 0.9;
354 var maxWidth = document.body.clientWidth * 0.9;
355 document.getElementById('bigimg').style.height = "";
356 document.getElementById('bigimg').style.width = "";
357 document.getElementById('bigimg').style.maxHeight = maxHeight + "px";
358 document.getElementById('bigimg').style.maxWidth = maxWidth + "px";
359 document.getElementById('bigimg').onload = function () {
360 var heightRatio = this.clientHeight / parseInt(this.style.maxHeight);
361 var widthRatio = this.clientWidth / parseInt(this.style.maxWidth);
362 if (heightRatio > 1 || widthRatio > 1) {
363 if (heightRatio > widthRatio) {
364 this.style.height = this.style.maxHeight;
366 this.style.width = this.style.maxWidth;
370 var offsetTop = this.offsetTop;
371 var offsetLeft = this.offsetLeft;
372 var par = this.offsetParent;
373 var ismsie = OpenLayers.Util.getBrowserName() == "msie";
374 while (par && !ismsie) {
375 offsetTop += par.offsetTop;
376 offsetLeft += par.offsetLeft;
377 par = par.offsetParent;
379 var icon = document.getElementById('bigimg_close');
380 icon.style.top = offsetTop;
381 icon.style.left = offsetLeft + this.clientWidth - icon.clientWidth;
384 document.getElementById('bigimg').src = href;
387 closeBigImage: function() {
388 document.getElementById('bigimg').src = "";
389 document.getElementById('bigimg').parentNode.innerHTML = document.getElementById('bigimg').parentNode.innerHTML;
390 document.getElementById('bigimg_container').style.display = "none";
394 tlCorner: function(map, margin) {
395 var bounds = map.calculateBounds();
396 var corner = new OpenLayers.LonLat(bounds.left, bounds.top);
397 var cornerAsPx = map.getPixelFromLonLat(corner);
398 cornerAsPx = cornerAsPx.add( +margin, +margin);
399 return map.getLonLatFromPixel(cornerAsPx);
402 trCorner: function(map, margin) {
403 var bounds = map.calculateBounds();
404 var corner = new OpenLayers.LonLat(bounds.right, bounds.top);
405 var cornerAsPx = map.getPixelFromLonLat(corner);
406 cornerAsPx = cornerAsPx.add( -margin, +margin);
407 return map.getLonLatFromPixel(cornerAsPx);
410 brCorner: function(map, margin) {
411 var bounds = map.calculateBounds();
412 var corner = new OpenLayers.LonLat(bounds.right, bounds.bottom);
413 var cornerAsPx = map.getPixelFromLonLat(corner);
414 cornerAsPx = cornerAsPx.add( -margin, -margin);
415 return map.getLonLatFromPixel(cornerAsPx);
418 blCorner: function(map, margin) {
419 var bounds = map.calculateBounds();
420 var corner = new OpenLayers.LonLat(bounds.left, bounds.bottom);
421 var cornerAsPx = map.getPixelFromLonLat(corner);
422 cornerAsPx = cornerAsPx.add( +margin, -margin);
423 return map.getLonLatFromPixel(cornerAsPx);
426 /* minimum bounds rectangle containing all feature locations.
427 * FIXME: if two features are close, but separated by 180th meridian,
428 * their mbr will span the whole earth. Actually, 179° lon and -170°
429 * lon are considerated very near.
431 mbr: function (layer) {
435 var mapProj = map.getProjectionObject();
436 var sypOrigProj = new OpenLayers.Projection("EPSG:4326");
438 for (var i =0; i < layer.features.length; i++) {
439 if (layer.features[i].cluster) {
440 features = features.concat(layer.features[i].cluster);
442 features = features.concat(layer.features);
451 if (features.length == 0) {
452 // keep default values
453 } else if (features.length == 1) {
454 // in case there's only one feature, we show an area of at least
456 var pos = features[0].geometry.getBounds().getCenterLonLat().clone();
457 var lonlat = pos.transform(mapProj, sypOrigProj);
459 minlon = Math.max (lonlat.lon - 2, -180);
460 maxlon = Math.min (lonlat.lon + 2, 180);
461 minlat = Math.max (lonlat.lat - 2, -90);
462 maxlat = Math.min (lonlat.lat + 2, 90);
464 for (var i = 0; i < features.length; i++) {
465 var pos = features[i].geometry.getBounds().getCenterLonLat().clone();
466 var lonlat = pos.transform(mapProj, sypOrigProj);
467 minlon = Math.min (lonlat.lon, minlon);
468 minlat = Math.min (lonlat.lat, minlat);
469 maxlon = Math.max (lonlat.lon, maxlon);
470 maxlat = Math.max (lonlat.lat, maxlat);
474 return [minlon, minlat, maxlon, maxlat];
478 displayUserMessage: function(message, status) {
479 var div = document.getElementById('message');
480 while (div.firstChild)
481 div.removeChild(div.firstChild);
482 var textNode = document.createTextNode(message);
485 div.style.color = "red";
488 div.style.color = "#FF8C00";
491 div.style.color = "green";
494 div.style.color = "black";
497 div.style.display = "block";
498 div.appendChild(textNode);
501 escapeHTML: function (str) {
506 replace(/&/gm, '&').
507 replace(/'/gm, ''').
508 replace(/"/gm, '"').
509 replace(/>/gm, '>').
510 replace(/</gm, '<');
515 // if possible, determine language with HTTP_ACCEPT_LANGUAGE instead of
516 // navigator.language
517 if (OpenLayers.Lang[SypStrings.language]) {
518 OpenLayers.Lang.setCode(SypStrings.language);
522 OpenLayers.Console.userError = function(error) {
523 SYP.Utils.displayUserMessage(error, "error");
526 // sometimes, especially when cache is clear, firefox does not compute
527 // correctly popup size. That's because at the end of getRenderedDimensions,
528 // dimensions of image is not known. Then, popup size is too small for its
529 // content. We work around the problem by checking that computed size is at
530 // least as big as content. To achieve that, we need to override
531 // OpenLayers.Popup.Anchored.prototype.updateSize to modify it slightly.
532 OpenLayers.Popup.Anchored.prototype.updateSize = function() {
535 window.setTimeout(function() { // timeout added by SYP
537 // determine actual render dimensions of the contents by putting its
538 // contents into a fake contentDiv (for the CSS) and then measuring it
539 var preparedHTML = "<div class='" + self.contentDisplayClass+ "'>" +
540 self.contentDiv.innerHTML +
543 var containerElement = (self.map) ? self.map.layerContainerDiv
545 var realSize = OpenLayers.Util.getRenderedDimensions(
546 preparedHTML, null, {
547 displayClass: self.displayClass,
548 containerElement: containerElement
553 * XXX: next four lines are added by SYP!
555 if (self.contentDiv) {
556 realSize.w = Math.max (realSize.w, self.contentDiv.scrollWidth);
557 realSize.h = Math.max (realSize.h, self.contentDiv.scrollHeight);
560 // is the "real" size of the div is safe to display in our map?
561 var safeSize = self.getSafeContentSize(realSize);
564 if (safeSize.equals(realSize)) {
565 //real size of content is small enough to fit on the map,
566 // so we use real size.
571 //make a new OL.Size object with the clipped dimensions
572 // set or null if not clipped.
573 var fixedSize = new OpenLayers.Size();
574 fixedSize.w = (safeSize.w < realSize.w) ? safeSize.w : null;
575 fixedSize.h = (safeSize.h < realSize.h) ? safeSize.h : null;
577 if (fixedSize.w && fixedSize.h) {
578 //content is too big in both directions, so we will use
579 // max popup size (safeSize), knowing well that it will
580 // overflow both ways.
583 //content is clipped in only one direction, so we need to
584 // run getRenderedDimensions() again with a fixed dimension
585 var clippedSize = OpenLayers.Util.getRenderedDimensions(
586 preparedHTML, fixedSize, {
587 displayClass: self.contentDisplayClass,
588 containerElement: containerElement
592 //if the clipped size is still the same as the safeSize,
593 // that means that our content must be fixed in the
594 // offending direction. If overflow is 'auto', this means
595 // we are going to have a scrollbar for sure, so we must
598 var currentOverflow = OpenLayers.Element.getStyle(
599 self.contentDiv, "overflow"
601 if ( (currentOverflow != "hidden") &&
602 (clippedSize.equals(safeSize)) ) {
603 var scrollBar = OpenLayers.Util.getScrollbarWidth();
605 clippedSize.h += scrollBar;
607 clippedSize.w += scrollBar;
611 newSize = self.getSafeContentSize(clippedSize);
614 self.setSize(newSize);