1 /* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
2 * license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
3 * full text of the license. */
6 * @requires OpenLayers/Renderer/Elements.js
10 * Class: OpenLayers.Renderer.SVG
13 * - <OpenLayers.Renderer.Elements>
15 OpenLayers.Renderer.SVG = OpenLayers.Class(OpenLayers.Renderer.Elements, {
21 xmlns: "http://www.w3.org/2000/svg",
27 xlinkns: "http://www.w3.org/1999/xlink",
31 * {Integer} Firefox has a limitation where values larger or smaller than
32 * about 15000 in an SVG document lock the browser up. This
38 * Property: translationParameters
39 * {Object} Hash with "x" and "y" properties
41 translationParameters: null,
44 * Property: symbolSize
45 * {Object} Cache for symbol sizes according to their svg coordinate space
56 * Constructor: OpenLayers.Renderer.SVG
59 * containerID - {String}
61 initialize: function(containerID) {
62 if (!this.supported()) {
65 OpenLayers.Renderer.Elements.prototype.initialize.apply(this,
67 this.translationParameters = {x: 0, y: 0};
68 this.isGecko = (navigator.userAgent.toLowerCase().indexOf("gecko/") != -1);
75 OpenLayers.Renderer.Elements.prototype.destroy.apply(this, arguments);
79 * APIMethod: supported
82 * {Boolean} Whether or not the browser supports the SVG renderer
84 supported: function() {
85 var svgFeature = "http://www.w3.org/TR/SVG11/feature#";
86 return (document.implementation &&
87 (document.implementation.hasFeature("org.w3c.svg", "1.0") ||
88 document.implementation.hasFeature(svgFeature + "SVG", "1.1") ||
89 document.implementation.hasFeature(svgFeature + "BasicStructure", "1.1") ));
93 * Method: inValidRange
94 * See #669 for more information
99 * xyOnly - {Boolean} whether or not to just check for x and y, which means
100 * to not take the current translation parameters into account if true.
103 * {Boolean} Whether or not the 'x' and 'y' coordinates are in the
106 inValidRange: function(x, y, xyOnly) {
107 var left = x + (xyOnly ? 0 : this.translationParameters.x);
108 var top = y + (xyOnly ? 0 : this.translationParameters.y);
109 return (left >= -this.MAX_PIXEL && left <= this.MAX_PIXEL &&
110 top >= -this.MAX_PIXEL && top <= this.MAX_PIXEL);
117 * extent - {<OpenLayers.Bounds>}
118 * resolutionChanged - {Boolean}
121 * {Boolean} true to notify the layer that the new extent does not exceed
122 * the coordinate range, and the features will not need to be redrawn.
125 setExtent: function(extent, resolutionChanged) {
126 OpenLayers.Renderer.Elements.prototype.setExtent.apply(this,
129 var resolution = this.getResolution();
130 var left = -extent.left / resolution;
131 var top = extent.top / resolution;
133 // If the resolution has changed, start over changing the corner, because
134 // the features will redraw.
135 if (resolutionChanged) {
139 var extentString = "0 0 " + this.size.w + " " + this.size.h;
141 this.rendererRoot.setAttributeNS(null, "viewBox", extentString);
142 this.translate(0, 0);
145 var inRange = this.translate(left - this.left, top - this.top);
147 // recenter the coordinate system
148 this.setExtent(extent, true);
156 * Transforms the SVG coordinate system
163 * {Boolean} true if the translation parameters are in the valid coordinates
164 * range, false otherwise.
166 translate: function(x, y) {
167 if (!this.inValidRange(x, y, true)) {
170 var transformString = "";
172 transformString = "translate(" + x + "," + y + ")";
174 this.root.setAttributeNS(null, "transform", transformString);
175 this.translationParameters = {x: x, y: y};
182 * Sets the size of the drawing surface.
185 * size - {<OpenLayers.Size>} The size of the drawing surface
187 setSize: function(size) {
188 OpenLayers.Renderer.prototype.setSize.apply(this, arguments);
190 this.rendererRoot.setAttributeNS(null, "width", this.size.w);
191 this.rendererRoot.setAttributeNS(null, "height", this.size.h);
195 * Method: getNodeType
198 * geometry - {<OpenLayers.Geometry>}
202 * {String} The corresponding node type for the specified geometry
204 getNodeType: function(geometry, style) {
206 switch (geometry.CLASS_NAME) {
207 case "OpenLayers.Geometry.Point":
208 if (style.externalGraphic) {
210 } else if (this.isComplexSymbol(style.graphicName)) {
216 case "OpenLayers.Geometry.Rectangle":
219 case "OpenLayers.Geometry.LineString":
220 nodeType = "polyline";
222 case "OpenLayers.Geometry.LinearRing":
223 nodeType = "polygon";
225 case "OpenLayers.Geometry.Polygon":
226 case "OpenLayers.Geometry.Curve":
227 case "OpenLayers.Geometry.Surface":
238 * Use to set all the style attributes to a SVG node.
240 * Takes care to adjust stroke width and point radius to be
241 * resolution-relative
244 * node - {SVGDomElement} An SVG element to decorate
246 * options - {Object} Currently supported options include
247 * 'isFilled' {Boolean} and
248 * 'isStroked' {Boolean}
250 setStyle: function(node, style, options) {
251 style = style || node._style;
252 options = options || node._options;
253 var r = parseFloat(node.getAttributeNS(null, "r"));
256 if (node._geometryClass == "OpenLayers.Geometry.Point" && r) {
257 node.style.visibility = "";
258 if (style.graphic === false) {
259 node.style.visibility = "hidden";
260 } else if (style.externalGraphic) {
261 pos = this.getPosition(node);
263 if (style.graphicTitle) {
264 node.setAttributeNS(null, "title", style.graphicTitle);
266 if (style.graphicWidth && style.graphicHeight) {
267 node.setAttributeNS(null, "preserveAspectRatio", "none");
269 var width = style.graphicWidth || style.graphicHeight;
270 var height = style.graphicHeight || style.graphicWidth;
271 width = width ? width : style.pointRadius*2;
272 height = height ? height : style.pointRadius*2;
273 var xOffset = (style.graphicXOffset != undefined) ?
274 style.graphicXOffset : -(0.5 * width);
275 var yOffset = (style.graphicYOffset != undefined) ?
276 style.graphicYOffset : -(0.5 * height);
278 var opacity = style.graphicOpacity || style.fillOpacity;
280 node.setAttributeNS(null, "x", (pos.x + xOffset).toFixed());
281 node.setAttributeNS(null, "y", (pos.y + yOffset).toFixed());
282 node.setAttributeNS(null, "width", width);
283 node.setAttributeNS(null, "height", height);
284 node.setAttributeNS(this.xlinkns, "href", style.externalGraphic);
285 node.setAttributeNS(null, "style", "opacity: "+opacity);
286 } else if (this.isComplexSymbol(style.graphicName)) {
287 // the symbol viewBox is three times as large as the symbol
288 var offset = style.pointRadius * 3;
289 var size = offset * 2;
290 var id = this.importSymbol(style.graphicName);
292 pos = this.getPosition(node);
293 widthFactor = this.symbolSize[id] / size;
295 // remove the node from the dom before we modify it. This
296 // prevents various rendering issues in Safari and FF
297 var parent = node.parentNode;
298 var nextSibling = node.nextSibling;
300 parent.removeChild(node);
303 node.setAttributeNS(this.xlinkns, "href", href);
304 node.setAttributeNS(null, "width", size);
305 node.setAttributeNS(null, "height", size);
306 node.setAttributeNS(null, "x", pos.x - offset);
307 node.setAttributeNS(null, "y", pos.y - offset);
309 // now that the node has all its new properties, insert it
310 // back into the dom where it was
312 parent.insertBefore(node, nextSibling);
314 parent.appendChild(node);
317 node.setAttributeNS(null, "r", style.pointRadius);
320 if (typeof style.rotation != "undefined" && pos) {
321 var rotation = OpenLayers.String.format(
322 "rotate(${0} ${1} ${2})", [style.rotation, pos.x, pos.y]);
323 node.setAttributeNS(null, "transform", rotation);
327 if (options.isFilled) {
328 node.setAttributeNS(null, "fill", style.fillColor);
329 node.setAttributeNS(null, "fill-opacity", style.fillOpacity);
331 node.setAttributeNS(null, "fill", "none");
334 if (options.isStroked) {
335 node.setAttributeNS(null, "stroke", style.strokeColor);
336 node.setAttributeNS(null, "stroke-opacity", style.strokeOpacity);
337 node.setAttributeNS(null, "stroke-width", style.strokeWidth * widthFactor);
338 node.setAttributeNS(null, "stroke-linecap", style.strokeLinecap);
339 // Hard-coded linejoin for now, to make it look the same as in VML.
340 // There is no strokeLinejoin property yet for symbolizers.
341 node.setAttributeNS(null, "stroke-linejoin", "round");
342 node.setAttributeNS(null, "stroke-dasharray", this.dashStyle(style,
345 node.setAttributeNS(null, "stroke", "none");
348 if (style.pointerEvents) {
349 node.setAttributeNS(null, "pointer-events", style.pointerEvents);
352 if (style.cursor != null) {
353 node.setAttributeNS(null, "cursor", style.cursor);
364 * widthFactor - {Number}
367 * {String} A SVG compliant 'stroke-dasharray' value
369 dashStyle: function(style, widthFactor) {
370 var w = style.strokeWidth * widthFactor;
372 switch (style.strokeDashstyle) {
376 return [1, 4 * w].join();
378 return [4 * w, 4 * w].join();
380 return [4 * w, 4 * w, 1, 4 * w].join();
382 return [8 * w, 4 * w].join();
384 return [8 * w, 4 * w, 1, 4 * w].join();
386 return style.strokeDashstyle.replace(/ /g, ",");
394 * type - {String} Kind of node to draw
395 * id - {String} Id for node
398 * {DOMElement} A new node of the given type and id
400 createNode: function(type, id) {
401 var node = document.createElementNS(this.xmlns, type);
403 node.setAttributeNS(null, "id", id);
409 * Method: nodeTypeCompare
412 * node - {SVGDomElement} An SVG element
413 * type - {String} Kind of node
416 * {Boolean} Whether or not the specified node is of the specified type
418 nodeTypeCompare: function(node, type) {
419 return (type == node.nodeName);
423 * Method: createRenderRoot
426 * {DOMElement} The specific render engine's root element
428 createRenderRoot: function() {
429 return this.nodeFactory(this.container.id + "_svgRoot", "svg");
436 * suffix - {String} suffix to append to the id
441 createRoot: function(suffix) {
442 return this.nodeFactory(this.container.id + suffix, "g");
449 * {DOMElement} The element to which we'll add the symbol definitions
451 createDefs: function() {
452 var defs = this.nodeFactory(this.container.id + "_defs", "defs");
453 this.rendererRoot.appendChild(defs);
457 /**************************************
459 * GEOMETRY DRAWING FUNCTIONS *
461 **************************************/
465 * This method is only called by the renderer itself.
468 * node - {DOMElement}
469 * geometry - {<OpenLayers.Geometry>}
472 * {DOMElement} or false if the renderer could not draw the point
474 drawPoint: function(node, geometry) {
475 return this.drawCircle(node, geometry, 1);
480 * This method is only called by the renderer itself.
483 * node - {DOMElement}
484 * geometry - {<OpenLayers.Geometry>}
488 * {DOMElement} or false if the renderer could not draw the circle
490 drawCircle: function(node, geometry, radius) {
491 var resolution = this.getResolution();
492 var x = (geometry.x / resolution + this.left);
493 var y = (this.top - geometry.y / resolution);
495 if (this.inValidRange(x, y)) {
496 node.setAttributeNS(null, "cx", x);
497 node.setAttributeNS(null, "cy", y);
498 node.setAttributeNS(null, "r", radius);
507 * Method: drawLineString
508 * This method is only called by the renderer itself.
511 * node - {DOMElement}
512 * geometry - {<OpenLayers.Geometry>}
515 * {DOMElement} or null if the renderer could not draw all components of
516 * the linestring, or false if nothing could be drawn
518 drawLineString: function(node, geometry) {
519 var componentsResult = this.getComponentsString(geometry.components);
520 if (componentsResult.path) {
521 node.setAttributeNS(null, "points", componentsResult.path);
522 return (componentsResult.complete ? node : null);
529 * Method: drawLinearRing
530 * This method is only called by the renderer itself.
533 * node - {DOMElement}
534 * geometry - {<OpenLayers.Geometry>}
537 * {DOMElement} or null if the renderer could not draw all components
538 * of the linear ring, or false if nothing could be drawn
540 drawLinearRing: function(node, geometry) {
541 var componentsResult = this.getComponentsString(geometry.components);
542 if (componentsResult.path) {
543 node.setAttributeNS(null, "points", componentsResult.path);
544 return (componentsResult.complete ? node : null);
551 * Method: drawPolygon
552 * This method is only called by the renderer itself.
555 * node - {DOMElement}
556 * geometry - {<OpenLayers.Geometry>}
559 * {DOMElement} or null if the renderer could not draw all components
560 * of the polygon, or false if nothing could be drawn
562 drawPolygon: function(node, geometry) {
566 var linearRingResult, path;
567 for (var j=0, len=geometry.components.length; j<len; j++) {
569 linearRingResult = this.getComponentsString(
570 geometry.components[j].components, " ");
571 path = linearRingResult.path;
574 complete = linearRingResult.complete && complete;
581 node.setAttributeNS(null, "d", d);
582 node.setAttributeNS(null, "fill-rule", "evenodd");
583 return complete ? node : null;
590 * Method: drawRectangle
591 * This method is only called by the renderer itself.
594 * node - {DOMElement}
595 * geometry - {<OpenLayers.Geometry>}
598 * {DOMElement} or false if the renderer could not draw the rectangle
600 drawRectangle: function(node, geometry) {
601 var resolution = this.getResolution();
602 var x = (geometry.x / resolution + this.left);
603 var y = (this.top - geometry.y / resolution);
605 if (this.inValidRange(x, y)) {
606 node.setAttributeNS(null, "x", x);
607 node.setAttributeNS(null, "y", y);
608 node.setAttributeNS(null, "width", geometry.width / resolution);
609 node.setAttributeNS(null, "height", geometry.height / resolution);
617 * Method: drawSurface
618 * This method is only called by the renderer itself.
621 * node - {DOMElement}
622 * geometry - {<OpenLayers.Geometry>}
625 * {DOMElement} or false if the renderer could not draw the surface
627 drawSurface: function(node, geometry) {
629 // create the svg path string representation
632 for (var i=0, len=geometry.components.length; i<len; i++) {
633 if ((i%3) == 0 && (i/3) == 0) {
634 var component = this.getShortString(geometry.components[i]);
635 if (!component) { draw = false; }
636 d = "M " + component;
637 } else if ((i%3) == 1) {
638 var component = this.getShortString(geometry.components[i]);
639 if (!component) { draw = false; }
640 d += " C " + component;
642 var component = this.getShortString(geometry.components[i]);
643 if (!component) { draw = false; }
644 d += " " + component;
649 node.setAttributeNS(null, "d", d);
658 * This method is only called by the renderer itself.
661 * featureId - {String}
663 * location - {<OpenLayers.Geometry.Point>}
665 drawText: function(featureId, style, location) {
666 var resolution = this.getResolution();
668 var x = (location.x / resolution + this.left);
669 var y = (location.y / resolution - this.top);
671 var label = this.nodeFactory(featureId + this.LABEL_ID_SUFFIX, "text");
672 var tspan = this.nodeFactory(featureId + this.LABEL_ID_SUFFIX + "_tspan", "tspan");
674 label.setAttributeNS(null, "x", x);
675 label.setAttributeNS(null, "y", -y);
676 label.setAttributeNS(null, "pointer-events", "none");
678 if (style.fontColor) {
679 label.setAttributeNS(null, "fill", style.fontColor);
681 if (style.fontFamily) {
682 label.setAttributeNS(null, "font-family", style.fontFamily);
684 if (style.fontSize) {
685 label.setAttributeNS(null, "font-size", style.fontSize);
687 if (style.fontWeight) {
688 label.setAttributeNS(null, "font-weight", style.fontWeight);
690 var align = style.labelAlign || "cm";
691 label.setAttributeNS(null, "text-anchor",
692 OpenLayers.Renderer.SVG.LABEL_ALIGN[align[0]] || "middle");
695 label.setAttributeNS(null, "dominant-baseline",
696 OpenLayers.Renderer.SVG.LABEL_ALIGN[align[1]] || "central");
698 tspan.setAttributeNS(null, "baseline-shift",
699 OpenLayers.Renderer.SVG.LABEL_VSHIFT[align[1]] || "-35%");
702 tspan.textContent = style.label;
704 if(!label.parentNode) {
705 label.appendChild(tspan);
706 this.textRoot.appendChild(label);
711 * Method: getComponentString
714 * components - {Array(<OpenLayers.Geometry.Point>)} Array of points
715 * separator - {String} character between coordinate pairs. Defaults to ","
718 * {Object} hash with properties "path" (the string created from the
719 * components and "complete" (false if the renderer was unable to
720 * draw all components)
722 getComponentsString: function(components, separator) {
725 var len = components.length;
727 var str, component, j;
728 for(var i=0; i<len; i++) {
729 component = components[i];
730 renderCmp.push(component);
731 str = this.getShortString(component);
735 // The current component is outside the valid range. Let's
736 // see if the previous or next component is inside the range.
737 // If so, add the coordinate of the intersection with the
738 // valid range bounds.
740 if (this.getShortString(components[i - 1])) {
741 strings.push(this.clipLine(components[i],
746 if (this.getShortString(components[i + 1])) {
747 strings.push(this.clipLine(components[i],
756 path: strings.join(separator || ","),
763 * Given two points (one inside the valid range, and one outside),
764 * clips the line betweeen the two points so that the new points are both
765 * inside the valid range.
768 * badComponent - {<OpenLayers.Geometry.Point>)} original geometry of the
770 * goodComponent - {<OpenLayers.Geometry.Point>)} original geometry of the
773 * {String} the SVG coordinate pair of the clipped point (like
774 * getShortString), or an empty string if both passed componets are at
777 clipLine: function(badComponent, goodComponent) {
778 if (goodComponent.equals(badComponent)) {
781 var resolution = this.getResolution();
782 var maxX = this.MAX_PIXEL - this.translationParameters.x;
783 var maxY = this.MAX_PIXEL - this.translationParameters.y;
784 var x1 = goodComponent.x / resolution + this.left;
785 var y1 = this.top - goodComponent.y / resolution;
786 var x2 = badComponent.x / resolution + this.left;
787 var y2 = this.top - badComponent.y / resolution;
789 if (x2 < -maxX || x2 > maxX) {
790 k = (y2 - y1) / (x2 - x1);
791 x2 = x2 < 0 ? -maxX : maxX;
792 y2 = y1 + (x2 - x1) * k;
794 if (y2 < -maxY || y2 > maxY) {
795 k = (x2 - x1) / (y2 - y1);
796 y2 = y2 < 0 ? -maxY : maxY;
797 x2 = x1 + (y2 - y1) * k;
799 return x2 + "," + y2;
803 * Method: getShortString
806 * point - {<OpenLayers.Geometry.Point>}
809 * {String} or false if point is outside the valid range
811 getShortString: function(point) {
812 var resolution = this.getResolution();
813 var x = (point.x / resolution + this.left);
814 var y = (this.top - point.y / resolution);
816 if (this.inValidRange(x, y)) {
824 * Method: getPosition
825 * Finds the position of an svg node.
828 * node - {DOMElement}
831 * {Object} hash with x and y properties, representing the coordinates
832 * within the svg coordinate system
834 getPosition: function(node) {
836 x: parseFloat(node.getAttributeNS(null, "cx")),
837 y: parseFloat(node.getAttributeNS(null, "cy"))
842 * Method: importSymbol
843 * add a new symbol definition from the rendererer's symbol hash
846 * graphicName - {String} name of the symbol to import
849 * {String} - id of the imported symbol
851 importSymbol: function (graphicName) {
853 // create svg defs tag
854 this.defs = this.createDefs();
856 var id = this.container.id + "-" + graphicName;
858 // check if symbol already exists in the defs
859 if (document.getElementById(id) != null) {
863 var symbol = OpenLayers.Renderer.symbol[graphicName];
865 throw new Error(graphicName + ' is not a valid symbol name');
869 var symbolNode = this.nodeFactory(id, "symbol");
870 var node = this.nodeFactory(null, "polygon");
871 symbolNode.appendChild(node);
872 var symbolExtent = new OpenLayers.Bounds(
873 Number.MAX_VALUE, Number.MAX_VALUE, 0, 0);
877 for (var i=0; i<symbol.length; i=i+2) {
880 symbolExtent.left = Math.min(symbolExtent.left, x);
881 symbolExtent.bottom = Math.min(symbolExtent.bottom, y);
882 symbolExtent.right = Math.max(symbolExtent.right, x);
883 symbolExtent.top = Math.max(symbolExtent.top, y);
884 points += " " + x + "," + y;
887 node.setAttributeNS(null, "points", points);
889 var width = symbolExtent.getWidth();
890 var height = symbolExtent.getHeight();
891 // create a viewBox three times as large as the symbol itself,
892 // to allow for strokeWidth being displayed correctly at the corners.
893 var viewBox = [symbolExtent.left - width,
894 symbolExtent.bottom - height, width * 3, height * 3];
895 symbolNode.setAttributeNS(null, "viewBox", viewBox.join(" "));
896 this.symbolSize[id] = Math.max(width, height) * 3;
898 this.defs.appendChild(symbolNode);
899 return symbolNode.id;
902 CLASS_NAME: "OpenLayers.Renderer.SVG"
906 * Constant: OpenLayers.Renderer.SVG.LABEL_ALIGN
909 OpenLayers.Renderer.SVG.LABEL_ALIGN = {
917 * Constant: OpenLayers.Renderer.SVG.LABEL_VSHIFT
920 OpenLayers.Renderer.SVG.LABEL_VSHIFT = {
922 // http://www.w3.org/Graphics/SVG/Test/20061213/htmlObjectHarness/full-text-align-02-b.html
923 // a baseline-shift of -70% shifts the text exactly from the
924 // bottom to the top of the baseline, so -35% moves the text to
925 // the center of the baseline.