source: trunk/zoo-project/zoo-api/js/ZOO-api.js @ 889

Last change on this file since 889 was 828, checked in by djay, 7 years ago

Add support for headers definition to requests run from js ZOO-API.

File size: 192.8 KB
Line 
1/**
2 * Author : René-Luc D'Hont
3 *
4 * Copyright 2010 3liz SARL. All rights reserved.
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
24
25/* Copyright (c) 2006-2011 by OpenLayers Contributors (see
26 * https://github.com/openlayers/openlayers/blob/master/authors.txt for full
27 * list of contributors). Published under the Clear BSD license.
28 * See http://svn.openlayers.org/trunk/openlayers/license.txt for the
29 * full text of the license.
30 */
31
32/**
33 * Class: ZOO
34 */
35ZOO = {
36  /**
37   * Constant: SERVICE_ACCEPTED
38   * {Integer} used for
39   */
40  SERVICE_ACCEPTED: 0,
41  /**
42   * Constant: SERVICE_STARTED
43   * {Integer} used for
44   */
45  SERVICE_STARTED: 1,
46  /**
47   * Constant: SERVICE_PAUSED
48   * {Integer} used for
49   */
50  SERVICE_PAUSED: 2,
51  /**
52   * Constant: SERVICE_SUCCEEDED
53   * {Integer} used for
54   */
55  SERVICE_SUCCEEDED: 3,
56  /**
57   * Constant: SERVICE_FAILED
58   * {Integer} used for
59   */
60  SERVICE_FAILED: 4,
61  /**
62   * Function: removeItem
63   * Remove an object from an array. Iterates through the array
64   *     to find the item, then removes it.
65   *
66   * Parameters:
67   * array - {Array}
68   * item - {Object}
69   *
70   * Return
71   * {Array} A reference to the array
72   */
73  removeItem: function(array, item) {
74    for(var i = array.length - 1; i >= 0; i--) {
75        if(array[i] == item) {
76            array.splice(i,1);
77        }
78    }
79    return array;
80  },
81  /**
82   * Function: indexOf
83   *
84   * Parameters:
85   * array - {Array}
86   * obj - {Object}
87   *
88   * Returns:
89   * {Integer} The index at, which the first object was found in the array.
90   *           If not found, returns -1.
91   */
92  indexOf: function(array, obj) {
93    for(var i=0, len=array.length; i<len; i++) {
94      if (array[i] == obj)
95        return i;
96    }
97    return -1;   
98  },
99  /**
100   * Function: extend
101   * Copy all properties of a source object to a destination object. Modifies
102   *     the passed in destination object.  Any properties on the source object
103   *     that are set to undefined will not be (re)set on the destination object.
104   *
105   * Parameters:
106   * destination - {Object} The object that will be modified
107   * source - {Object} The object with properties to be set on the destination
108   *
109   * Returns:
110   * {Object} The destination object.
111   */
112  extend: function(destination, source) {
113    destination = destination || {};
114    if(source) {
115      for(var property in source) {
116        var value = source[property];
117        if(value !== undefined)
118          destination[property] = value;
119      }
120    }
121    return destination;
122  },
123  /**
124   * Function: rad
125   *
126   * Parameters:
127   * x - {Float}
128   *
129   * Returns:
130   * {Float}
131   */
132  rad: function(x) {return x*Math.PI/180;},
133  /**
134   * Function: distVincenty
135   * Given two objects representing points with geographic coordinates, this
136   *     calculates the distance between those points on the surface of an
137   *     ellipsoid.
138   *
139   * Parameters:
140   * p1 - {<ZOO.Geometry.Point>} (or any object with both .x, .y properties)
141   * p2 - {<ZOO.Geometry.Point>} (or any object with both .x, .y properties)
142   *
143   * Returns:
144   * {Float} The distance (in km) between the two input points as measured on an
145   *     ellipsoid.  Note that the input point objects must be in geographic
146   *     coordinates (decimal degrees) and the return distance is in kilometers.
147   */
148  distVincenty: function(p1, p2) {
149    var a = 6378137, b = 6356752.3142,  f = 1/298.257223563;
150    var L = ZOO.rad(p2.x - p1.y);
151    var U1 = Math.atan((1-f) * Math.tan(ZOO.rad(p1.y)));
152    var U2 = Math.atan((1-f) * Math.tan(ZOO.rad(p2.y)));
153    var sinU1 = Math.sin(U1), cosU1 = Math.cos(U1);
154    var sinU2 = Math.sin(U2), cosU2 = Math.cos(U2);
155    var lambda = L, lambdaP = 2*Math.PI;
156    var iterLimit = 20;
157    while (Math.abs(lambda-lambdaP) > 1e-12 && --iterLimit>0) {
158        var sinLambda = Math.sin(lambda), cosLambda = Math.cos(lambda);
159        var sinSigma = Math.sqrt((cosU2*sinLambda) * (cosU2*sinLambda) +
160        (cosU1*sinU2-sinU1*cosU2*cosLambda) * (cosU1*sinU2-sinU1*cosU2*cosLambda));
161        if (sinSigma==0) {
162            return 0;  // co-incident points
163        }
164        var cosSigma = sinU1*sinU2 + cosU1*cosU2*cosLambda;
165        var sigma = Math.atan2(sinSigma, cosSigma);
166        var alpha = Math.asin(cosU1 * cosU2 * sinLambda / sinSigma);
167        var cosSqAlpha = Math.cos(alpha) * Math.cos(alpha);
168        var cos2SigmaM = cosSigma - 2*sinU1*sinU2/cosSqAlpha;
169        var C = f/16*cosSqAlpha*(4+f*(4-3*cosSqAlpha));
170        lambdaP = lambda;
171        lambda = L + (1-C) * f * Math.sin(alpha) *
172        (sigma + C*sinSigma*(cos2SigmaM+C*cosSigma*(-1+2*cos2SigmaM*cos2SigmaM)));
173    }
174    if (iterLimit==0) {
175        return NaN;  // formula failed to converge
176    }
177    var uSq = cosSqAlpha * (a*a - b*b) / (b*b);
178    var A = 1 + uSq/16384*(4096+uSq*(-768+uSq*(320-175*uSq)));
179    var B = uSq/1024 * (256+uSq*(-128+uSq*(74-47*uSq)));
180    var deltaSigma = B*sinSigma*(cos2SigmaM+B/4*(cosSigma*(-1+2*cos2SigmaM*cos2SigmaM)-
181        B/6*cos2SigmaM*(-3+4*sinSigma*sinSigma)*(-3+4*cos2SigmaM*cos2SigmaM)));
182    var s = b*A*(sigma-deltaSigma);
183    var d = s.toFixed(3)/1000; // round to 1mm precision
184    return d;
185  },
186  /**
187   * Function: Class
188   * Method used to create ZOO classes. Includes support for
189   *     multiple inheritance.
190   */
191  Class: function() {
192    var Class = function() {
193      this.initialize.apply(this, arguments);
194    };
195    var extended = {};
196    var parent;
197    for(var i=0; i<arguments.length; ++i) {
198      if(typeof arguments[i] == "function") {
199        // get the prototype of the superclass
200        parent = arguments[i].prototype;
201      } else {
202        // in this case we're extending with the prototype
203        parent = arguments[i];
204      }
205      ZOO.extend(extended, parent);
206    }
207    Class.prototype = extended;
208
209    return Class;
210  },
211  /**
212   * Function: UpdateStatus
213   * Method used to update the status of the process
214   *
215   * Parameters:
216   * env - {Object} The environment object
217   * value - {Float} the status value between 0 to 100
218   */
219  UpdateStatus: function(env,value) {
220    return ZOOUpdateStatus(env,value);
221  }
222};
223
224/**
225 * Class: ZOO.String
226 * Contains convenience methods for string manipulation
227 */
228ZOO.String = {
229  /**
230   * Function: startsWith
231   * Test whether a string starts with another string.
232   *
233   * Parameters:
234   * str - {String} The string to test.
235   * sub - {Sring} The substring to look for.
236   * 
237   * Returns:
238   * {Boolean} The first string starts with the second.
239   */
240  startsWith: function(str, sub) {
241    return (str.indexOf(sub) == 0);
242  },
243  /**
244   * Function: contains
245   * Test whether a string contains another string.
246   *
247   * Parameters:
248   * str - {String} The string to test.
249   * sub - {String} The substring to look for.
250   *
251   * Returns:
252   * {Boolean} The first string contains the second.
253   */
254  contains: function(str, sub) {
255    return (str.indexOf(sub) != -1);
256  },
257  /**
258   * Function: trim
259   * Removes leading and trailing whitespace characters from a string.
260   *
261   * Parameters:
262   * str - {String} The (potentially) space padded string.  This string is not
263   *     modified.
264   *
265   * Returns:
266   * {String} A trimmed version of the string with all leading and
267   *     trailing spaces removed.
268   */
269  trim: function(str) {
270    return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
271  },
272  /**
273   * Function: camelize
274   * Camel-case a hyphenated string.
275   *     Ex. "chicken-head" becomes "chickenHead", and
276   *     "-chicken-head" becomes "ChickenHead".
277   *
278   * Parameters:
279   * str - {String} The string to be camelized.  The original is not modified.
280   *
281   * Returns:
282   * {String} The string, camelized
283   *
284   */
285  camelize: function(str) {
286    var oStringList = str.split('-');
287    var camelizedString = oStringList[0];
288    for (var i=1, len=oStringList.length; i<len; i++) {
289      var s = oStringList[i];
290      camelizedString += s.charAt(0).toUpperCase() + s.substring(1);
291    }
292    return camelizedString;
293  },
294  /**
295   * Property: tokenRegEx
296   * Used to find tokens in a string.
297   * Examples: ${a}, ${a.b.c}, ${a-b}, ${5}
298   */
299  tokenRegEx:  /\$\{([\w.]+?)\}/g,
300  /**
301   * Property: numberRegEx
302   * Used to test strings as numbers.
303   */
304  numberRegEx: /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/,
305  /**
306   * Function: isNumeric
307   * Determine whether a string contains only a numeric value.
308   *
309   * Examples:
310   * (code)
311   * ZOO.String.isNumeric("6.02e23") // true
312   * ZOO.String.isNumeric("12 dozen") // false
313   * ZOO.String.isNumeric("4") // true
314   * ZOO.String.isNumeric(" 4 ") // false
315   * (end)
316   *
317   * Returns:
318   * {Boolean} String contains only a number.
319   */
320  isNumeric: function(value) {
321    return ZOO.String.numberRegEx.test(value);
322  },
323  /**
324   * Function: numericIf
325   * Converts a string that appears to be a numeric value into a number.
326   *
327   * Returns
328   * {Number|String} a Number if the passed value is a number, a String
329   *     otherwise.
330   */
331  numericIf: function(value) {
332    return ZOO.String.isNumeric(value) ? parseFloat(value) : value;
333  }
334};
335
336/**
337 * Class: ZOO.Class
338 * Object for creating CLASS
339 */
340ZOO.Class = function() {
341  var len = arguments.length;
342  var P = arguments[0];
343  var F = arguments[len-1];
344  var C = typeof F.initialize == "function" ?
345    F.initialize :
346    function(){ P.prototype.initialize.apply(this, arguments); };
347
348  if (len > 1) {
349    var newArgs = [C, P].concat(
350          Array.prototype.slice.call(arguments).slice(1, len-1), F);
351    ZOO.inherit.apply(null, newArgs);
352  } else {
353    C.prototype = F;
354  }
355  return C;
356};
357/**
358 * Function: create
359 * Function for creating CLASS
360 */
361ZOO.Class.create = function() {
362  return function() {
363    if (arguments && arguments[0] != ZOO.Class.isPrototype) {
364      this.initialize.apply(this, arguments);
365    }
366  };
367};
368/**
369 * Function: inherit
370 * Function for inheriting CLASS
371 */
372ZOO.Class.inherit = function (P) {
373  var C = function() {
374   P.call(this);
375  };
376  var newArgs = [C].concat(Array.prototype.slice.call(arguments));
377  ZOO.inherit.apply(null, newArgs);
378  return C.prototype;
379};
380/**
381 * Function: inherit
382 * Function for inheriting CLASS
383 */
384ZOO.inherit = function(C, P) {
385  var F = function() {};
386  F.prototype = P.prototype;
387  C.prototype = new F;
388  var i, l, o;
389  for(i=2, l=arguments.length; i<l; i++) {
390    o = arguments[i];
391    if(typeof o === "function") {
392      o = o.prototype;
393    }
394    ZOO.Util.extend(C.prototype, o);
395  }
396};
397/**
398 * Class: ZOO.Util
399 * Object for utilities
400 */
401ZOO.Util = ZOO.Util || {};
402/**
403 * Function: extend
404 * Function for extending object
405 */
406ZOO.Util.extend = function(destination, source) {
407  destination = destination || {};
408  if (source) {
409    for (var property in source) {
410      var value = source[property];
411      if (value !== undefined) {
412        destination[property] = value;
413      }
414    }
415  }
416  return destination;
417};
418
419ZOO._=function(str){
420    return ZOOTranslate(str);
421};
422
423/**
424 * Class: ZOO.Request
425 * Contains convenience methods for working with ZOORequest which
426 *     replace XMLHttpRequest. Because of we are not in a browser
427 *     JavaScript environment, ZOO Project provides a method to
428 *     query servers which is based on curl : ZOORequest.
429 */
430ZOO.Request = {
431  /**
432   * Function: GET
433   * Send an HTTP GET request.
434   *
435   * Parameters:
436   * url - {String} The URL to request.
437   * params - {Object} Params to add to the url
438   * headers - {Object/Array}  A key-value object of headers
439   *
440   * Returns:
441   * {String} Request result.
442   */
443    Get: function(url,params,headers) {
444    var paramsArray = [];
445    for (var key in params) {
446      var value = params[key];
447      if ((value != null) && (typeof value != 'function')) {
448        var encodedValue;
449        if (typeof value == 'object' && value.constructor == Array) {
450          /* value is an array; encode items and separate with "," */
451          var encodedItemArray = [];
452          for (var itemIndex=0, len=value.length; itemIndex<len; itemIndex++) {
453            encodedItemArray.push(encodeURIComponent(value[itemIndex]));
454          }
455          encodedValue = encodedItemArray.join(",");
456        }
457        else {
458          /* value is a string; simply encode */
459          encodedValue = encodeURIComponent(value);
460        }
461        paramsArray.push(encodeURIComponent(key) + "=" + encodedValue);
462      }
463    }
464    var paramString = paramsArray.join("&");
465    if(paramString.length > 0) {
466      var separator = (url.indexOf('?') > -1) ? '&' : '?';
467      url += separator + paramString;
468    }
469    if(!(headers instanceof Array)) {
470        var headersArray = [];
471        for (var name in headers) {
472            headersArray.push(name+': '+headers[name]); 
473        }
474        headers = headersArray;
475    }
476    return ZOORequest('GET',url,headers);
477  },
478  /**
479   * Function: POST
480   * Send an HTTP POST request.
481   *
482   * Parameters:
483   * url - {String} The URL to request.
484   * body - {String} The request's body to send.
485   * headers - {Object} A key-value object of headers to push to
486   *     the request's head
487   *
488   * Returns:
489   * {String} Request result.
490   */
491  Post: function(url,body,headers) {
492    if(!(headers instanceof Array)) {
493      var headersArray = [];
494      for (var name in headers) {
495        headersArray.push(name+': '+headers[name]); 
496      }
497      headers = headersArray;
498    }
499    return ZOORequest('POST',url,body,headers);
500  }
501};
502
503/**
504 * Class: ZOO.Bounds
505 * Instances of this class represent bounding boxes.  Data stored as left,
506 *     bottom, right, top floats. All values are initialized to null,
507 *     however, you should make sure you set them before using the bounds
508 *     for anything.
509 */
510ZOO.Bounds = ZOO.Class({
511  /**
512   * Property: left
513   * {Number} Minimum horizontal coordinate.
514   */
515  left: null,
516  /**
517   * Property: bottom
518   * {Number} Minimum vertical coordinate.
519   */
520  bottom: null,
521  /**
522   * Property: right
523   * {Number} Maximum horizontal coordinate.
524   */
525  right: null,
526  /**
527   * Property: top
528   * {Number} Maximum vertical coordinate.
529   */
530  top: null,
531  /**
532   * Constructor: ZOO.Bounds
533   * Construct a new bounds object.
534   *
535   * Parameters:
536   * left - {Number} The left bounds of the box.  Note that for width
537   *        calculations, this is assumed to be less than the right value.
538   * bottom - {Number} The bottom bounds of the box.  Note that for height
539   *          calculations, this is assumed to be more than the top value.
540   * right - {Number} The right bounds.
541   * top - {Number} The top bounds.
542   */
543  initialize: function(left, bottom, right, top) {
544    if (left != null)
545      this.left = parseFloat(left);
546    if (bottom != null)
547      this.bottom = parseFloat(bottom);
548    if (right != null)
549      this.right = parseFloat(right);
550    if (top != null)
551      this.top = parseFloat(top);
552  },
553  /**
554   * Method: clone
555   * Create a cloned instance of this bounds.
556   *
557   * Returns:
558   * {<ZOO.Bounds>} A fresh copy of the bounds
559   */
560  clone:function() {
561    return new ZOO.Bounds(this.left, this.bottom, 
562                          this.right, this.top);
563  },
564  /**
565   * Method: equals
566   * Test a two bounds for equivalence.
567   *
568   * Parameters:
569   * bounds - {<ZOO.Bounds>}
570   *
571   * Returns:
572   * {Boolean} The passed-in bounds object has the same left,
573   *           right, top, bottom components as this.  Note that if bounds
574   *           passed in is null, returns false.
575   */
576  equals:function(bounds) {
577    var equals = false;
578    if (bounds != null)
579        equals = ((this.left == bounds.left) && 
580                  (this.right == bounds.right) &&
581                  (this.top == bounds.top) && 
582                  (this.bottom == bounds.bottom));
583    return equals;
584  },
585  /**
586   * Method: toString
587   *
588   * Returns:
589   * {String} String representation of bounds object.
590   *          (ex.<i>"left-bottom=(5,42) right-top=(10,45)"</i>)
591   */
592  toString:function() {
593    return ( "left-bottom=(" + this.left + "," + this.bottom + ")"
594              + " right-top=(" + this.right + "," + this.top + ")" );
595  },
596  /**
597   * APIMethod: toArray
598   *
599   * Returns:
600   * {Array} array of left, bottom, right, top
601   */
602  toArray: function() {
603    return [this.left, this.bottom, this.right, this.top];
604  },
605  /**
606   * Method: toBBOX
607   *
608   * Parameters:
609   * decimal - {Integer} How many significant digits in the bbox coords?
610   *                     Default is 6
611   *
612   * Returns:
613   * {String} Simple String representation of bounds object.
614   *          (ex. <i>"5,42,10,45"</i>)
615   */
616  toBBOX:function(decimal) {
617    if (decimal== null)
618      decimal = 6; 
619    var mult = Math.pow(10, decimal);
620    var bbox = Math.round(this.left * mult) / mult + "," + 
621               Math.round(this.bottom * mult) / mult + "," + 
622               Math.round(this.right * mult) / mult + "," + 
623               Math.round(this.top * mult) / mult;
624    return bbox;
625  },
626  /**
627   * Method: toGeometry
628   * Create a new polygon geometry based on this bounds.
629   *
630   * Returns:
631   * {<ZOO.Geometry.Polygon>} A new polygon with the coordinates
632   *     of this bounds.
633   */
634  toGeometry: function() {
635    return new ZOO.Geometry.Polygon([
636      new ZOO.Geometry.LinearRing([
637        new ZOO.Geometry.Point(this.left, this.bottom),
638        new ZOO.Geometry.Point(this.right, this.bottom),
639        new ZOO.Geometry.Point(this.right, this.top),
640        new ZOO.Geometry.Point(this.left, this.top)
641      ])
642    ]);
643  },
644  /**
645   * Method: getWidth
646   *
647   * Returns:
648   * {Float} The width of the bounds
649   */
650  getWidth:function() {
651    return (this.right - this.left);
652  },
653  /**
654   * Method: getHeight
655   *
656   * Returns:
657   * {Float} The height of the bounds (top minus bottom).
658   */
659  getHeight:function() {
660    return (this.top - this.bottom);
661  },
662  /**
663   * Method: add
664   *
665   * Parameters:
666   * x - {Float}
667   * y - {Float}
668   *
669   * Returns:
670   * {<ZOO.Bounds>} A new bounds whose coordinates are the same as
671   *     this, but shifted by the passed-in x and y values.
672   */
673  add:function(x, y) {
674    if ( (x == null) || (y == null) )
675      return null;
676    return new ZOO.Bounds(this.left + x, this.bottom + y,
677                                 this.right + x, this.top + y);
678  },
679  /**
680   * Method: extend
681   * Extend the bounds to include the point, lonlat, or bounds specified.
682   *     Note, this function assumes that left < right and bottom < top.
683   *
684   * Parameters:
685   * object - {Object} Can be Point, or Bounds
686   */
687  extend:function(object) {
688    var bounds = null;
689    if (object) {
690      // clear cached center location
691      switch(object.CLASS_NAME) {
692        case "ZOO.Geometry.Point":
693          bounds = new ZOO.Bounds(object.x, object.y,
694                                         object.x, object.y);
695          break;
696        case "ZOO.Bounds":   
697          bounds = object;
698          break;
699      }
700      if (bounds) {
701        if ( (this.left == null) || (bounds.left < this.left))
702          this.left = bounds.left;
703        if ( (this.bottom == null) || (bounds.bottom < this.bottom) )
704          this.bottom = bounds.bottom;
705        if ( (this.right == null) || (bounds.right > this.right) )
706          this.right = bounds.right;
707        if ( (this.top == null) || (bounds.top > this.top) )
708          this.top = bounds.top;
709      }
710    }
711  },
712  /**
713   * APIMethod: contains
714   *
715   * Parameters:
716   * x - {Float}
717   * y - {Float}
718   * inclusive - {Boolean} Whether or not to include the border.
719   *     Default is true.
720   *
721   * Returns:
722   * {Boolean} Whether or not the passed-in coordinates are within this
723   *     bounds.
724   */
725  contains:function(x, y, inclusive) {
726     //set default
727     if (inclusive == null)
728       inclusive = true;
729     if (x == null || y == null)
730       return false;
731     x = parseFloat(x);
732     y = parseFloat(y);
733
734     var contains = false;
735     if (inclusive)
736       contains = ((x >= this.left) && (x <= this.right) && 
737                   (y >= this.bottom) && (y <= this.top));
738     else
739       contains = ((x > this.left) && (x < this.right) && 
740                   (y > this.bottom) && (y < this.top));
741     return contains;
742  },
743  /**
744   * Method: intersectsBounds
745   * Determine whether the target bounds intersects this bounds.  Bounds are
746   *     considered intersecting if any of their edges intersect or if one
747   *     bounds contains the other.
748   *
749   * Parameters:
750   * bounds - {<ZOO.Bounds>} The target bounds.
751   * inclusive - {Boolean} Treat coincident borders as intersecting.  Default
752   *     is true.  If false, bounds that do not overlap but only touch at the
753   *     border will not be considered as intersecting.
754   *
755   * Returns:
756   * {Boolean} The passed-in bounds object intersects this bounds.
757   */
758  intersectsBounds:function(bounds, inclusive) {
759    if (inclusive == null)
760      inclusive = true;
761    var intersects = false;
762    var mightTouch = (
763        this.left == bounds.right ||
764        this.right == bounds.left ||
765        this.top == bounds.bottom ||
766        this.bottom == bounds.top
767    );
768    if (inclusive || !mightTouch) {
769      var inBottom = (
770          ((bounds.bottom >= this.bottom) && (bounds.bottom <= this.top)) ||
771          ((this.bottom >= bounds.bottom) && (this.bottom <= bounds.top))
772          );
773      var inTop = (
774          ((bounds.top >= this.bottom) && (bounds.top <= this.top)) ||
775          ((this.top > bounds.bottom) && (this.top < bounds.top))
776          );
777      var inLeft = (
778          ((bounds.left >= this.left) && (bounds.left <= this.right)) ||
779          ((this.left >= bounds.left) && (this.left <= bounds.right))
780          );
781      var inRight = (
782          ((bounds.right >= this.left) && (bounds.right <= this.right)) ||
783          ((this.right >= bounds.left) && (this.right <= bounds.right))
784          );
785      intersects = ((inBottom || inTop) && (inLeft || inRight));
786    }
787    return intersects;
788  },
789  /**
790   * Method: containsBounds
791   * Determine whether the target bounds is contained within this bounds.
792   *
793   * bounds - {<ZOO.Bounds>} The target bounds.
794   * partial - {Boolean} If any of the target corners is within this bounds
795   *     consider the bounds contained.  Default is false.  If true, the
796   *     entire target bounds must be contained within this bounds.
797   * inclusive - {Boolean} Treat shared edges as contained.  Default is
798   *     true.
799   *
800   * Returns:
801   * {Boolean} The passed-in bounds object is contained within this bounds.
802   */
803  containsBounds:function(bounds, partial, inclusive) {
804    if (partial == null)
805      partial = false;
806    if (inclusive == null)
807      inclusive = true;
808    var bottomLeft  = this.contains(bounds.left, bounds.bottom, inclusive);
809    var bottomRight = this.contains(bounds.right, bounds.bottom, inclusive);
810    var topLeft  = this.contains(bounds.left, bounds.top, inclusive);
811    var topRight = this.contains(bounds.right, bounds.top, inclusive);
812    return (partial) ? (bottomLeft || bottomRight || topLeft || topRight)
813                     : (bottomLeft && bottomRight && topLeft && topRight);
814  },
815  CLASS_NAME: 'ZOO.Bounds'
816});
817
818/**
819 * Class: ZOO.Projection
820 * Class for coordinate transforms between coordinate systems.
821 *     Depends on the zoo-proj4js library. zoo-proj4js library
822 *     is loaded by the ZOO Kernel with zoo-api.
823 */
824ZOO.Projection = ZOO.Class({
825  /**
826   * Property: proj
827   * {Object} Proj4js.Proj instance.
828   */
829  proj: null,
830  /**
831   * Property: projCode
832   * {String}
833   */
834  projCode: null,
835  /**
836   * Constructor: ZOO.Projection
837   * This class offers several methods for interacting with a wrapped
838   *     zoo-pro4js projection object.
839   *
840   * Parameters:
841   * projCode - {String} A string identifying the Well Known Identifier for
842   *    the projection.
843   * options - {Object} An optional object to set additional properties.
844   *
845   * Returns:
846   * {<ZOO.Projection>} A projection object.
847   */
848  initialize: function(projCode, options) {
849    ZOO.extend(this, options);
850    this.projCode = projCode;
851    if (Proj4js) {
852      this.proj = new Proj4js.Proj(projCode);
853    }
854  },
855  /**
856   * Method: getCode
857   * Get the string SRS code.
858   *
859   * Returns:
860   * {String} The SRS code.
861   */
862  getCode: function() {
863    return this.proj ? this.proj.srsCode : this.projCode;
864  },
865  /**
866   * Method: getUnits
867   * Get the units string for the projection -- returns null if
868   *     zoo-proj4js is not available.
869   *
870   * Returns:
871   * {String} The units abbreviation.
872   */
873  getUnits: function() {
874    return this.proj ? this.proj.units : null;
875  },
876  /**
877   * Method: toString
878   * Convert projection to string (getCode wrapper).
879   *
880   * Returns:
881   * {String} The projection code.
882   */
883  toString: function() {
884    return this.getCode();
885  },
886  /**
887   * Method: equals
888   * Test equality of two projection instances.  Determines equality based
889   *     soley on the projection code.
890   *
891   * Returns:
892   * {Boolean} The two projections are equivalent.
893   */
894  equals: function(projection) {
895    if (projection && projection.getCode)
896      return this.getCode() == projection.getCode();
897    else
898      return false;
899  },
900  /* Method: destroy
901   * Destroy projection object.
902   */
903  destroy: function() {
904    this.proj = null;
905    this.projCode = null;
906  },
907  CLASS_NAME: 'ZOO.Projection'
908});
909/**
910 * Method: transform
911 * Transform a point coordinate from one projection to another.  Note that
912 *     the input point is transformed in place.
913 *
914 * Parameters:
915 * point - {{ZOO.Geometry.Point> | Object} An object with x and y
916 *     properties representing coordinates in those dimensions.
917 * sourceProj - {ZOO.Projection} Source map coordinate system
918 * destProj - {ZOO.Projection} Destination map coordinate system
919 *
920 * Returns:
921 * point - {object} A transformed coordinate.  The original point is modified.
922 */
923ZOO.Projection.transform = function(point, source, dest) {
924    if (source.proj && dest.proj)
925        point = Proj4js.transform(source.proj, dest.proj, point);
926    return point;
927};
928
929/**
930 * Class: ZOO.Format
931 * Base class for format reading/writing a variety of formats. Subclasses
932 *     of ZOO.Format are expected to have read and write methods.
933 */
934ZOO.Format = ZOO.Class({
935  /**
936   * Property: options
937   * {Object} A reference to options passed to the constructor.
938   */
939  options:null,
940  /**
941   * Property: externalProjection
942   * {<ZOO.Projection>} When passed a externalProjection and
943   *     internalProjection, the format will reproject the geometries it
944   *     reads or writes. The externalProjection is the projection used by
945   *     the content which is passed into read or which comes out of write.
946   *     In order to reproject, a projection transformation function for the
947   *     specified projections must be available. This support is provided
948   *     via zoo-proj4js.
949   */
950  externalProjection: null,
951  /**
952   * Property: internalProjection
953   * {<ZOO.Projection>} When passed a externalProjection and
954   *     internalProjection, the format will reproject the geometries it
955   *     reads or writes. The internalProjection is the projection used by
956   *     the geometries which are returned by read or which are passed into
957   *     write.  In order to reproject, a projection transformation function
958   *     for the specified projections must be available. This support is
959   *     provided via zoo-proj4js.
960   */
961  internalProjection: null,
962  /**
963   * Property: data
964   * {Object} When <keepData> is true, this is the parsed string sent to
965   *     <read>.
966   */
967  data: null,
968  /**
969   * Property: keepData
970   * {Object} Maintain a reference (<data>) to the most recently read data.
971   *     Default is false.
972   */
973  keepData: false,
974  /**
975   * Constructor: ZOO.Format
976   * Instances of this class are not useful.  See one of the subclasses.
977   *
978   * Parameters:
979   * options - {Object} An optional object with properties to set on the
980   *           format
981   *
982   * Valid options:
983   * keepData - {Boolean} If true, upon <read>, the data property will be
984   *     set to the parsed object (e.g. the json or xml object).
985   *
986   * Returns:
987   * An instance of ZOO.Format
988   */
989  initialize: function(options) {
990    ZOO.extend(this, options);
991    this.options = options;
992  },
993  /**
994   * Method: destroy
995   * Clean up.
996   */
997  destroy: function() {
998  },
999  /**
1000   * Method: read
1001   * Read data from a string, and return an object whose type depends on the
1002   * subclass.
1003   *
1004   * Parameters:
1005   * data - {string} Data to read/parse.
1006   *
1007   * Returns:
1008   * Depends on the subclass
1009   */
1010  read: function(data) {
1011  },
1012  /**
1013   * Method: write
1014   * Accept an object, and return a string.
1015   *
1016   * Parameters:
1017   * object - {Object} Object to be serialized
1018   *
1019   * Returns:
1020   * {String} A string representation of the object.
1021   */
1022  write: function(data) {
1023  },
1024  CLASS_NAME: 'ZOO.Format'
1025});
1026/**
1027 * Class: ZOO.Format.WKT
1028 * Class for reading and writing Well-Known Text. Create a new instance
1029 * with the <ZOO.Format.WKT> constructor.
1030 *
1031 * Inherits from:
1032 *  - <ZOO.Format>
1033 */
1034ZOO.Format.WKT = ZOO.Class(ZOO.Format, {
1035  /**
1036   * Constructor: ZOO.Format.WKT
1037   * Create a new parser for WKT
1038   *
1039   * Parameters:
1040   * options - {Object} An optional object whose properties will be set on
1041   *           this instance
1042   *
1043   * Returns:
1044   * {<ZOO.Format.WKT>} A new WKT parser.
1045   */
1046  initialize: function(options) {
1047    this.regExes = {
1048      'typeStr': /^\s*(\w+)\s*\(\s*(.*)\s*\)\s*$/,
1049      'spaces': /\s+/,
1050      'parenComma': /\)\s*,\s*\(/,
1051      'doubleParenComma': /\)\s*\)\s*,\s*\(\s*\(/,  // can't use {2} here
1052      'trimParens': /^\s*\(?(.*?)\)?\s*$/
1053    };
1054    ZOO.Format.prototype.initialize.apply(this, [options]);
1055  },
1056  /**
1057   * Method: read
1058   * Deserialize a WKT string and return a vector feature or an
1059   *     array of vector features.  Supports WKT for POINT,
1060   *     MULTIPOINT, LINESTRING, MULTILINESTRING, POLYGON,
1061   *     MULTIPOLYGON, and GEOMETRYCOLLECTION.
1062   *
1063   * Parameters:
1064   * wkt - {String} A WKT string
1065   *
1066   * Returns:
1067   * {<ZOO.Feature.Vector>|Array} A feature or array of features for
1068   *     GEOMETRYCOLLECTION WKT.
1069   */
1070  read: function(wkt) {
1071    var features, type, str;
1072    var matches = this.regExes.typeStr.exec(wkt);
1073    if(matches) {
1074      type = matches[1].toLowerCase();
1075      str = matches[2];
1076      if(this.parse[type]) {
1077        features = this.parse[type].apply(this, [str]);
1078      }
1079      if (this.internalProjection && this.externalProjection) {
1080        if (features && 
1081            features.CLASS_NAME == "ZOO.Feature") {
1082          features.geometry.transform(this.externalProjection,
1083                                      this.internalProjection);
1084        } else if (features &&
1085            type != "geometrycollection" &&
1086            typeof features == "object") {
1087          for (var i=0, len=features.length; i<len; i++) {
1088            var component = features[i];
1089            component.geometry.transform(this.externalProjection,
1090                                         this.internalProjection);
1091          }
1092        }
1093      }
1094    }   
1095    return features;
1096  },
1097  /**
1098   * Method: write
1099   * Serialize a feature or array of features into a WKT string.
1100   *
1101   * Parameters:
1102   * features - {<ZOO.Feature.Vector>|Array} A feature or array of
1103   *            features
1104   *
1105   * Returns:
1106   * {String} The WKT string representation of the input geometries
1107   */
1108  write: function(features) {
1109    var collection, geometry, type, data, isCollection;
1110    if(features.constructor == Array) {
1111      collection = features;
1112      isCollection = true;
1113    } else {
1114      collection = [features];
1115      isCollection = false;
1116    }
1117    var pieces = [];
1118    if(isCollection)
1119      pieces.push('GEOMETRYCOLLECTION(');
1120    for(var i=0, len=collection.length; i<len; ++i) {
1121      if(isCollection && i>0)
1122        pieces.push(',');
1123      geometry = collection[i].geometry;
1124      type = geometry.CLASS_NAME.split('.')[2].toLowerCase();
1125      if(!this.extract[type])
1126        return null;
1127      if (this.internalProjection && this.externalProjection) {
1128        geometry = geometry.clone();
1129        geometry.transform(this.internalProjection, 
1130                          this.externalProjection);
1131      }                       
1132      data = this.extract[type].apply(this, [geometry]);
1133      pieces.push(type.toUpperCase() + '(' + data + ')');
1134    }
1135    if(isCollection)
1136      pieces.push(')');
1137    return pieces.join('');
1138  },
1139  /**
1140   * Property: extract
1141   * Object with properties corresponding to the geometry types.
1142   * Property values are functions that do the actual data extraction.
1143   */
1144  extract: {
1145    /**
1146     * Return a space delimited string of point coordinates.
1147     * @param {<ZOO.Geometry.Point>} point
1148     * @returns {String} A string of coordinates representing the point
1149     */
1150    'point': function(point) {
1151      return point.x + ' ' + point.y;
1152    },
1153    /**
1154     * Return a comma delimited string of point coordinates from a multipoint.
1155     * @param {<ZOO.Geometry.MultiPoint>} multipoint
1156     * @returns {String} A string of point coordinate strings representing
1157     *                  the multipoint
1158     */
1159    'multipoint': function(multipoint) {
1160      var array = [];
1161      for(var i=0, len=multipoint.components.length; i<len; ++i) {
1162        array.push(this.extract.point.apply(this, [multipoint.components[i]]));
1163      }
1164      return array.join(',');
1165    },
1166    /**
1167     * Return a comma delimited string of point coordinates from a line.
1168     * @param {<ZOO.Geometry.LineString>} linestring
1169     * @returns {String} A string of point coordinate strings representing
1170     *                  the linestring
1171     */
1172    'linestring': function(linestring) {
1173      var array = [];
1174      for(var i=0, len=linestring.components.length; i<len; ++i) {
1175        array.push(this.extract.point.apply(this, [linestring.components[i]]));
1176      }
1177      return array.join(',');
1178    },
1179    /**
1180     * Return a comma delimited string of linestring strings from a multilinestring.
1181     * @param {<ZOO.Geometry.MultiLineString>} multilinestring
1182     * @returns {String} A string of of linestring strings representing
1183     *                  the multilinestring
1184     */
1185    'multilinestring': function(multilinestring) {
1186      var array = [];
1187      for(var i=0, len=multilinestring.components.length; i<len; ++i) {
1188        array.push('(' +
1189            this.extract.linestring.apply(this, [multilinestring.components[i]]) +
1190            ')');
1191      }
1192      return array.join(',');
1193    },
1194    /**
1195     * Return a comma delimited string of linear ring arrays from a polygon.
1196     * @param {<ZOO.Geometry.Polygon>} polygon
1197     * @returns {String} An array of linear ring arrays representing the polygon
1198     */
1199    'polygon': function(polygon) {
1200      var array = [];
1201      for(var i=0, len=polygon.components.length; i<len; ++i) {
1202        array.push('(' +
1203            this.extract.linestring.apply(this, [polygon.components[i]]) +
1204            ')');
1205      }
1206      return array.join(',');
1207    },
1208    /**
1209     * Return an array of polygon arrays from a multipolygon.
1210     * @param {<ZOO.Geometry.MultiPolygon>} multipolygon
1211     * @returns {Array} An array of polygon arrays representing
1212     *                  the multipolygon
1213     */
1214    'multipolygon': function(multipolygon) {
1215      var array = [];
1216      for(var i=0, len=multipolygon.components.length; i<len; ++i) {
1217        array.push('(' +
1218            this.extract.polygon.apply(this, [multipolygon.components[i]]) +
1219            ')');
1220      }
1221      return array.join(',');
1222    }
1223  },
1224  /**
1225   * Property: parse
1226   * Object with properties corresponding to the geometry types.
1227   *     Property values are functions that do the actual parsing.
1228   */
1229  parse: {
1230    /**
1231     * Method: parse.point
1232     * Return point feature given a point WKT fragment.
1233     *
1234     * Parameters:
1235     * str - {String} A WKT fragment representing the point
1236     * Returns:
1237     * {<ZOO.Feature>} A point feature
1238     */
1239    'point': function(str) {
1240       var coords = ZOO.String.trim(str).split(this.regExes.spaces);
1241            return new ZOO.Feature(
1242                new ZOO.Geometry.Point(coords[0], coords[1])
1243            );
1244    },
1245    /**
1246     * Method: parse.multipoint
1247     * Return a multipoint feature given a multipoint WKT fragment.
1248     *
1249     * Parameters:
1250     * str - {String} A WKT fragment representing the multipoint
1251     *
1252     * Returns:
1253     * {<ZOO.Feature>} A multipoint feature
1254     */
1255    'multipoint': function(str) {
1256       var points = ZOO.String.trim(str).split(',');
1257       var components = [];
1258       for(var i=0, len=points.length; i<len; ++i) {
1259         components.push(this.parse.point.apply(this, [points[i]]).geometry);
1260       }
1261       return new ZOO.Feature(
1262           new ZOO.Geometry.MultiPoint(components)
1263           );
1264    },
1265    /**
1266     * Method: parse.linestring
1267     * Return a linestring feature given a linestring WKT fragment.
1268     *
1269     * Parameters:
1270     * str - {String} A WKT fragment representing the linestring
1271     *
1272     * Returns:
1273     * {<ZOO.Feature>} A linestring feature
1274     */
1275    'linestring': function(str) {
1276      var points = ZOO.String.trim(str).split(',');
1277      var components = [];
1278      for(var i=0, len=points.length; i<len; ++i) {
1279        components.push(this.parse.point.apply(this, [points[i]]).geometry);
1280      }
1281      return new ZOO.Feature(
1282          new ZOO.Geometry.LineString(components)
1283          );
1284    },
1285    /**
1286     * Method: parse.multilinestring
1287     * Return a multilinestring feature given a multilinestring WKT fragment.
1288     *
1289     * Parameters:
1290     * str - {String} A WKT fragment representing the multilinestring
1291     *
1292     * Returns:
1293     * {<ZOO.Feature>} A multilinestring feature
1294     */
1295    'multilinestring': function(str) {
1296      var line;
1297      var lines = ZOO.String.trim(str).split(this.regExes.parenComma);
1298      var components = [];
1299      for(var i=0, len=lines.length; i<len; ++i) {
1300        line = lines[i].replace(this.regExes.trimParens, '$1');
1301        components.push(this.parse.linestring.apply(this, [line]).geometry);
1302      }
1303      return new ZOO.Feature(
1304          new ZOO.Geometry.MultiLineString(components)
1305          );
1306    },
1307    /**
1308     * Method: parse.polygon
1309     * Return a polygon feature given a polygon WKT fragment.
1310     *
1311     * Parameters:
1312     * str - {String} A WKT fragment representing the polygon
1313     *
1314     * Returns:
1315     * {<ZOO.Feature>} A polygon feature
1316     */
1317    'polygon': function(str) {
1318       var ring, linestring, linearring;
1319       var rings = ZOO.String.trim(str).split(this.regExes.parenComma);
1320       var components = [];
1321       for(var i=0, len=rings.length; i<len; ++i) {
1322         ring = rings[i].replace(this.regExes.trimParens, '$1');
1323         linestring = this.parse.linestring.apply(this, [ring]).geometry;
1324         linearring = new ZOO.Geometry.LinearRing(linestring.components);
1325         components.push(linearring);
1326       }
1327       return new ZOO.Feature(
1328           new ZOO.Geometry.Polygon(components)
1329           );
1330    },
1331    /**
1332     * Method: parse.multipolygon
1333     * Return a multipolygon feature given a multipolygon WKT fragment.
1334     *
1335     * Parameters:
1336     * str - {String} A WKT fragment representing the multipolygon
1337     *
1338     * Returns:
1339     * {<ZOO.Feature>} A multipolygon feature
1340     */
1341    'multipolygon': function(str) {
1342      var polygon;
1343      var polygons = ZOO.String.trim(str).split(this.regExes.doubleParenComma);
1344      var components = [];
1345      for(var i=0, len=polygons.length; i<len; ++i) {
1346        polygon = polygons[i].replace(this.regExes.trimParens, '$1');
1347        components.push(this.parse.polygon.apply(this, [polygon]).geometry);
1348      }
1349      return new ZOO.Feature(
1350          new ZOO.Geometry.MultiPolygon(components)
1351          );
1352    },
1353    /**
1354     * Method: parse.geometrycollection
1355     * Return an array of features given a geometrycollection WKT fragment.
1356     *
1357     * Parameters:
1358     * str - {String} A WKT fragment representing the geometrycollection
1359     *
1360     * Returns:
1361     * {Array} An array of ZOO.Feature
1362     */
1363    'geometrycollection': function(str) {
1364      // separate components of the collection with |
1365      str = str.replace(/,\s*([A-Za-z])/g, '|$1');
1366      var wktArray = ZOO.String.trim(str).split('|');
1367      var components = [];
1368      for(var i=0, len=wktArray.length; i<len; ++i) {
1369        components.push(ZOO.Format.WKT.prototype.read.apply(this,[wktArray[i]]));
1370      }
1371      return components;
1372    }
1373  },
1374  CLASS_NAME: 'ZOO.Format.WKT'
1375});
1376/**
1377 * Class: ZOO.Format.JSON
1378 * A parser to read/write JSON safely. Create a new instance with the
1379 *     <ZOO.Format.JSON> constructor.
1380 *
1381 * Inherits from:
1382 *  - <ZOO.Format>
1383 */
1384ZOO.Format.JSON = ZOO.Class(ZOO.Format, {
1385  /**
1386   * Property: indent
1387   * {String} For "pretty" printing, the indent string will be used once for
1388   *     each indentation level.
1389   */
1390  indent: "    ",
1391  /**
1392   * Property: space
1393   * {String} For "pretty" printing, the space string will be used after
1394   *     the ":" separating a name/value pair.
1395   */
1396  space: " ",
1397  /**
1398   * Property: newline
1399   * {String} For "pretty" printing, the newline string will be used at the
1400   *     end of each name/value pair or array item.
1401   */
1402  newline: "\n",
1403  /**
1404   * Property: level
1405   * {Integer} For "pretty" printing, this is incremented/decremented during
1406   *     serialization.
1407   */
1408  level: 0,
1409  /**
1410   * Property: pretty
1411   * {Boolean} Serialize with extra whitespace for structure.  This is set
1412   *     by the <write> method.
1413   */
1414  pretty: false,
1415  /**
1416   * Constructor: ZOO.Format.JSON
1417   * Create a new parser for JSON.
1418   *
1419   * Parameters:
1420   * options - {Object} An optional object whose properties will be set on
1421   *     this instance.
1422   */
1423  initialize: function(options) {
1424    ZOO.Format.prototype.initialize.apply(this, [options]);
1425  },
1426  /**
1427   * Method: read
1428   * Deserialize a json string.
1429   *
1430   * Parameters:
1431   * json - {String} A JSON string
1432   * filter - {Function} A function which will be called for every key and
1433   *     value at every level of the final result. Each value will be
1434   *     replaced by the result of the filter function. This can be used to
1435   *     reform generic objects into instances of classes, or to transform
1436   *     date strings into Date objects.
1437   *     
1438   * Returns:
1439   * {Object} An object, array, string, or number .
1440   */
1441  read: function(json, filter) {
1442    /**
1443     * Parsing happens in three stages. In the first stage, we run the text
1444     *     against a regular expression which looks for non-JSON
1445     *     characters. We are especially concerned with '()' and 'new'
1446     *     because they can cause invocation, and '=' because it can cause
1447     *     mutation. But just to be safe, we will reject all unexpected
1448     *     characters.
1449     */
1450    try {
1451      if (/^[\],:{}\s]*$/.test(json.replace(/\\["\\\/bfnrtu]/g, '@').
1452                          replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
1453                          replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
1454        /**
1455         * In the second stage we use the eval function to compile the
1456         *     text into a JavaScript structure. The '{' operator is
1457         *     subject to a syntactic ambiguity in JavaScript - it can
1458         *     begin a block or an object literal. We wrap the text in
1459         *     parens to eliminate the ambiguity.
1460         */
1461        var object = eval('(' + json + ')');
1462        /**
1463         * In the optional third stage, we recursively walk the new
1464         *     structure, passing each name/value pair to a filter
1465         *     function for possible transformation.
1466         */
1467        if(typeof filter === 'function') {
1468          function walk(k, v) {
1469            if(v && typeof v === 'object') {
1470              for(var i in v) {
1471                if(v.hasOwnProperty(i)) {
1472                  v[i] = walk(i, v[i]);
1473                }
1474              }
1475            }
1476            return filter(k, v);
1477          }
1478          object = walk('', object);
1479        }
1480        if(this.keepData) {
1481          this.data = object;
1482        }
1483        return object;
1484      }
1485    } catch(e) {
1486      // Fall through if the regexp test fails.
1487    }
1488    return null;
1489  },
1490  /**
1491   * Method: write
1492   * Serialize an object into a JSON string.
1493   *
1494   * Parameters:
1495   * value - {String} The object, array, string, number, boolean or date
1496   *     to be serialized.
1497   * pretty - {Boolean} Structure the output with newlines and indentation.
1498   *     Default is false.
1499   *
1500   * Returns:
1501   * {String} The JSON string representation of the input value.
1502   */
1503  write: function(value, pretty) {
1504    this.pretty = !!pretty;
1505    var json = null;
1506    var type = typeof value;
1507    if(this.serialize[type]) {
1508      try {
1509        json = this.serialize[type].apply(this, [value]);
1510      } catch(err) {
1511        //OpenLayers.Console.error("Trouble serializing: " + err);
1512      }
1513    }
1514    return json;
1515  },
1516  /**
1517   * Method: writeIndent
1518   * Output an indentation string depending on the indentation level.
1519   *
1520   * Returns:
1521   * {String} An appropriate indentation string.
1522   */
1523  writeIndent: function() {
1524    var pieces = [];
1525    if(this.pretty) {
1526      for(var i=0; i<this.level; ++i) {
1527        pieces.push(this.indent);
1528      }
1529    }
1530    return pieces.join('');
1531  },
1532  /**
1533   * Method: writeNewline
1534   * Output a string representing a newline if in pretty printing mode.
1535   *
1536   * Returns:
1537   * {String} A string representing a new line.
1538   */
1539  writeNewline: function() {
1540    return (this.pretty) ? this.newline : '';
1541  },
1542  /**
1543   * Method: writeSpace
1544   * Output a string representing a space if in pretty printing mode.
1545   *
1546   * Returns:
1547   * {String} A space.
1548   */
1549  writeSpace: function() {
1550    return (this.pretty) ? this.space : '';
1551  },
1552  /**
1553   * Property: serialize
1554   * Object with properties corresponding to the serializable data types.
1555   *     Property values are functions that do the actual serializing.
1556   */
1557  serialize: {
1558    /**
1559     * Method: serialize.object
1560     * Transform an object into a JSON string.
1561     *
1562     * Parameters:
1563     * object - {Object} The object to be serialized.
1564     *
1565     * Returns:
1566     * {String} A JSON string representing the object.
1567     */
1568    'object': function(object) {
1569       // three special objects that we want to treat differently
1570       if(object == null)
1571         return "null";
1572       if(object.constructor == Date)
1573         return this.serialize.date.apply(this, [object]);
1574       if(object.constructor == Array)
1575         return this.serialize.array.apply(this, [object]);
1576       var pieces = ['{'];
1577       this.level += 1;
1578       var key, keyJSON, valueJSON;
1579
1580       var addComma = false;
1581       for(key in object) {
1582         if(object.hasOwnProperty(key)) {
1583           // recursive calls need to allow for sub-classing
1584           keyJSON = ZOO.Format.JSON.prototype.write.apply(this,
1585                                                           [key, this.pretty]);
1586           valueJSON = ZOO.Format.JSON.prototype.write.apply(this,
1587                                                             [object[key], this.pretty]);
1588           if(keyJSON != null && valueJSON != null) {
1589             if(addComma)
1590               pieces.push(',');
1591             pieces.push(this.writeNewline(), this.writeIndent(),
1592                         keyJSON, ':', this.writeSpace(), valueJSON);
1593             addComma = true;
1594           }
1595         }
1596       }
1597       this.level -= 1;
1598       pieces.push(this.writeNewline(), this.writeIndent(), '}');
1599       return pieces.join('');
1600    },
1601    /**
1602     * Method: serialize.array
1603     * Transform an array into a JSON string.
1604     *
1605     * Parameters:
1606     * array - {Array} The array to be serialized
1607     *
1608     * Returns:
1609     * {String} A JSON string representing the array.
1610     */
1611    'array': function(array) {
1612      var json;
1613      var pieces = ['['];
1614      this.level += 1;
1615      for(var i=0, len=array.length; i<len; ++i) {
1616        // recursive calls need to allow for sub-classing
1617        json = ZOO.Format.JSON.prototype.write.apply(this,
1618                                                     [array[i], this.pretty]);
1619        if(json != null) {
1620          if(i > 0)
1621            pieces.push(',');
1622          pieces.push(this.writeNewline(), this.writeIndent(), json);
1623        }
1624      }
1625      this.level -= 1;   
1626      pieces.push(this.writeNewline(), this.writeIndent(), ']');
1627      return pieces.join('');
1628    },
1629    /**
1630     * Method: serialize.string
1631     * Transform a string into a JSON string.
1632     *
1633     * Parameters:
1634     * string - {String} The string to be serialized
1635     *
1636     * Returns:
1637     * {String} A JSON string representing the string.
1638     */
1639    'string': function(string) {
1640      var m = {
1641                '\b': '\\b',
1642                '\t': '\\t',
1643                '\n': '\\n',
1644                '\f': '\\f',
1645                '\r': '\\r',
1646                '"' : '\\"',
1647                '\\': '\\\\'
1648      };
1649      if(/["\\\x00-\x1f]/.test(string)) {
1650        return '"' + string.replace(/([\x00-\x1f\\"])/g, function(a, b) {
1651            var c = m[b];
1652            if(c)
1653              return c;
1654            c = b.charCodeAt();
1655            return '\\u00' +
1656            Math.floor(c / 16).toString(16) +
1657            (c % 16).toString(16);
1658        }) + '"';
1659      }
1660      return '"' + string + '"';
1661    },
1662    /**
1663     * Method: serialize.number
1664     * Transform a number into a JSON string.
1665     *
1666     * Parameters:
1667     * number - {Number} The number to be serialized.
1668     *
1669     * Returns:
1670     * {String} A JSON string representing the number.
1671     */
1672    'number': function(number) {
1673      return isFinite(number) ? String(number) : "null";
1674    },
1675    /**
1676     * Method: serialize.boolean
1677     * Transform a boolean into a JSON string.
1678     *
1679     * Parameters:
1680     * bool - {Boolean} The boolean to be serialized.
1681     *
1682     * Returns:
1683     * {String} A JSON string representing the boolean.
1684     */
1685    'boolean': function(bool) {
1686      return String(bool);
1687    },
1688    /**
1689     * Method: serialize.date
1690     * Transform a date into a JSON string.
1691     *
1692     * Parameters:
1693     * date - {Date} The date to be serialized.
1694     *
1695     * Returns:
1696     * {String} A JSON string representing the date.
1697     */
1698    'date': function(date) {   
1699      function format(number) {
1700        // Format integers to have at least two digits.
1701        return (number < 10) ? '0' + number : number;
1702      }
1703      return '"' + date.getFullYear() + '-' +
1704        format(date.getMonth() + 1) + '-' +
1705        format(date.getDate()) + 'T' +
1706        format(date.getHours()) + ':' +
1707        format(date.getMinutes()) + ':' +
1708        format(date.getSeconds()) + '"';
1709    }
1710  },
1711  CLASS_NAME: 'ZOO.Format.JSON'
1712});
1713/**
1714 * Class: ZOO.Format.GeoJSON
1715 * Read and write GeoJSON. Create a new parser with the
1716 *     <ZOO.Format.GeoJSON> constructor.
1717 *
1718 * Inherits from:
1719 *  - <ZOO.Format.JSON>
1720 */
1721ZOO.Format.GeoJSON = ZOO.Class(ZOO.Format.JSON, {
1722  /**
1723   * Constructor: ZOO.Format.GeoJSON
1724   * Create a new parser for GeoJSON.
1725   *
1726   * Parameters:
1727   * options - {Object} An optional object whose properties will be set on
1728   *     this instance.
1729   */
1730  initialize: function(options) {
1731    ZOO.Format.JSON.prototype.initialize.apply(this, [options]);
1732  },
1733  /**
1734   * Method: read
1735   * Deserialize a GeoJSON string.
1736   *
1737   * Parameters:
1738   * json - {String} A GeoJSON string
1739   * type - {String} Optional string that determines the structure of
1740   *     the output.  Supported values are "Geometry", "Feature", and
1741   *     "FeatureCollection".  If absent or null, a default of
1742   *     "FeatureCollection" is assumed.
1743   * filter - {Function} A function which will be called for every key and
1744   *     value at every level of the final result. Each value will be
1745   *     replaced by the result of the filter function. This can be used to
1746   *     reform generic objects into instances of classes, or to transform
1747   *     date strings into Date objects.
1748   *
1749   * Returns:
1750   * {Object} The return depends on the value of the type argument. If type
1751   *     is "FeatureCollection" (the default), the return will be an array
1752   *     of <ZOO.Feature>. If type is "Geometry", the input json
1753   *     must represent a single geometry, and the return will be an
1754   *     <ZOO.Geometry>.  If type is "Feature", the input json must
1755   *     represent a single feature, and the return will be an
1756   *     <ZOO.Feature>.
1757   */
1758  read: function(json, type, filter) {
1759    type = (type) ? type : "FeatureCollection";
1760    var results = null;
1761    var obj = null;
1762    if (typeof json == "string")
1763      obj = ZOO.Format.JSON.prototype.read.apply(this,[json, filter]);
1764    else
1765      obj = json;
1766    if(!obj) {
1767      //ZOO.Console.error("Bad JSON: " + json);
1768    } else if(typeof(obj.type) != "string") {
1769      //ZOO.Console.error("Bad GeoJSON - no type: " + json);
1770    } else if(this.isValidType(obj, type)) {
1771      switch(type) {
1772        case "Geometry":
1773          try {
1774            results = this.parseGeometry(obj);
1775          } catch(err) {
1776            //ZOO.Console.error(err);
1777          }
1778          break;
1779        case "Feature":
1780          try {
1781            results = this.parseFeature(obj);
1782            results.type = "Feature";
1783          } catch(err) {
1784            //ZOO.Console.error(err);
1785          }
1786          break;
1787        case "FeatureCollection":
1788          // for type FeatureCollection, we allow input to be any type
1789          results = [];
1790          switch(obj.type) {
1791            case "Feature":
1792              try {
1793                results.push(this.parseFeature(obj));
1794              } catch(err) {
1795                results = null;
1796                //ZOO.Console.error(err);
1797              }
1798              break;
1799            case "FeatureCollection":
1800              for(var i=0, len=obj.features.length; i<len; ++i) {
1801                try {
1802                  results.push(this.parseFeature(obj.features[i]));
1803                } catch(err) {
1804                  results = null;
1805                  //ZOO.Console.error(err);
1806                }
1807              }
1808              break;
1809            default:
1810              try {
1811                var geom = this.parseGeometry(obj);
1812                results.push(new ZOO.Feature(geom));
1813              } catch(err) {
1814                results = null;
1815                //ZOO.Console.error(err);
1816              }
1817          }
1818          break;
1819      }
1820    }
1821    return results;
1822  },
1823  /**
1824   * Method: isValidType
1825   * Check if a GeoJSON object is a valid representative of the given type.
1826   *
1827   * Returns:
1828   * {Boolean} The object is valid GeoJSON object of the given type.
1829   */
1830  isValidType: function(obj, type) {
1831    var valid = false;
1832    switch(type) {
1833      case "Geometry":
1834        if(ZOO.indexOf(
1835              ["Point", "MultiPoint", "LineString", "MultiLineString",
1836              "Polygon", "MultiPolygon", "Box", "GeometryCollection"],
1837              obj.type) == -1) {
1838          // unsupported geometry type
1839          //ZOO.Console.error("Unsupported geometry type: " +obj.type);
1840        } else {
1841          valid = true;
1842        }
1843        break;
1844      case "FeatureCollection":
1845        // allow for any type to be converted to a feature collection
1846        valid = true;
1847        break;
1848      default:
1849        // for Feature types must match
1850        if(obj.type == type) {
1851          valid = true;
1852        } else {
1853          //ZOO.Console.error("Cannot convert types from " +obj.type + " to " + type);
1854        }
1855    }
1856    return valid;
1857  },
1858  /**
1859   * Method: parseFeature
1860   * Convert a feature object from GeoJSON into an
1861   *     <ZOO.Feature>.
1862   *
1863   * Parameters:
1864   * obj - {Object} An object created from a GeoJSON object
1865   *
1866   * Returns:
1867   * {<ZOO.Feature>} A feature.
1868   */
1869  parseFeature: function(obj) {
1870    var feature, geometry, attributes, bbox;
1871    attributes = (obj.properties) ? obj.properties : {};
1872    bbox = (obj.geometry && obj.geometry.bbox) || obj.bbox;
1873    try {
1874      geometry = this.parseGeometry(obj.geometry);
1875    } catch(err) {
1876      // deal with bad geometries
1877      throw err;
1878    }
1879    feature = new ZOO.Feature(geometry, attributes);
1880    if(bbox)
1881      feature.bounds = ZOO.Bounds.fromArray(bbox);
1882    if(obj.id)
1883      feature.fid = obj.id;
1884    return feature;
1885  },
1886  /**
1887   * Method: parseGeometry
1888   * Convert a geometry object from GeoJSON into an <ZOO.Geometry>.
1889   *
1890   * Parameters:
1891   * obj - {Object} An object created from a GeoJSON object
1892   *
1893   * Returns:
1894   * {<ZOO.Geometry>} A geometry.
1895   */
1896  parseGeometry: function(obj) {
1897    if (obj == null)
1898      return null;
1899    var geometry, collection = false;
1900    if(obj.type == "GeometryCollection") {
1901      if(!(obj.geometries instanceof Array)) {
1902        throw "GeometryCollection must have geometries array: " + obj;
1903      }
1904      var numGeom = obj.geometries.length;
1905      var components = new Array(numGeom);
1906      for(var i=0; i<numGeom; ++i) {
1907        components[i] = this.parseGeometry.apply(
1908            this, [obj.geometries[i]]
1909            );
1910      }
1911      geometry = new ZOO.Geometry.Collection(components);
1912      collection = true;
1913    } else {
1914      if(!(obj.coordinates instanceof Array)) {
1915        throw "Geometry must have coordinates array: " + obj;
1916      }
1917      if(!this.parseCoords[obj.type.toLowerCase()]) {
1918        throw "Unsupported geometry type: " + obj.type;
1919      }
1920      try {
1921        geometry = this.parseCoords[obj.type.toLowerCase()].apply(
1922            this, [obj.coordinates]
1923            );
1924      } catch(err) {
1925        // deal with bad coordinates
1926        throw err;
1927      }
1928    }
1929        // We don't reproject collections because the children are reprojected
1930        // for us when they are created.
1931    if (this.internalProjection && this.externalProjection && !collection) {
1932      geometry.transform(this.externalProjection, 
1933          this.internalProjection); 
1934    }                       
1935    return geometry;
1936  },
1937  /**
1938   * Property: parseCoords
1939   * Object with properties corresponding to the GeoJSON geometry types.
1940   *     Property values are functions that do the actual parsing.
1941   */
1942  parseCoords: {
1943    /**
1944     * Method: parseCoords.point
1945     * Convert a coordinate array from GeoJSON into an
1946     *     <ZOO.Geometry.Point>.
1947     *
1948     * Parameters:
1949     * array - {Object} The coordinates array from the GeoJSON fragment.
1950     *
1951     * Returns:
1952     * {<ZOO.Geometry.Point>} A geometry.
1953     */
1954    "point": function(array) {
1955      if(array.length != 2) {
1956        throw "Only 2D points are supported: " + array;
1957      }
1958      return new ZOO.Geometry.Point(array[0], array[1]);
1959    },
1960    /**
1961     * Method: parseCoords.multipoint
1962     * Convert a coordinate array from GeoJSON into an
1963     *     <ZOO.Geometry.MultiPoint>.
1964     *
1965     * Parameters:
1966     * array - {Object} The coordinates array from the GeoJSON fragment.
1967     *
1968     * Returns:
1969     * {<ZOO.Geometry.MultiPoint>} A geometry.
1970     */
1971    "multipoint": function(array) {
1972      var points = [];
1973      var p = null;
1974      for(var i=0, len=array.length; i<len; ++i) {
1975        try {
1976          p = this.parseCoords["point"].apply(this, [array[i]]);
1977        } catch(err) {
1978          throw err;
1979        }
1980        points.push(p);
1981      }
1982      return new ZOO.Geometry.MultiPoint(points);
1983    },
1984    /**
1985     * Method: parseCoords.linestring
1986     * Convert a coordinate array from GeoJSON into an
1987     *     <ZOO.Geometry.LineString>.
1988     *
1989     * Parameters:
1990     * array - {Object} The coordinates array from the GeoJSON fragment.
1991     *
1992     * Returns:
1993     * {<ZOO.Geometry.LineString>} A geometry.
1994     */
1995    "linestring": function(array) {
1996      var points = [];
1997      var p = null;
1998      for(var i=0, len=array.length; i<len; ++i) {
1999        try {
2000          p = this.parseCoords["point"].apply(this, [array[i]]);
2001        } catch(err) {
2002          throw err;
2003        }
2004        points.push(p);
2005      }
2006      return new ZOO.Geometry.LineString(points);
2007    },
2008    /**
2009     * Method: parseCoords.multilinestring
2010     * Convert a coordinate array from GeoJSON into an
2011     *     <ZOO.Geometry.MultiLineString>.
2012     *
2013     * Parameters:
2014     * array - {Object} The coordinates array from the GeoJSON fragment.
2015     *
2016     * Returns:
2017     * {<ZOO.Geometry.MultiLineString>} A geometry.
2018     */
2019    "multilinestring": function(array) {
2020      var lines = [];
2021      var l = null;
2022      for(var i=0, len=array.length; i<len; ++i) {
2023        try {
2024          l = this.parseCoords["linestring"].apply(this, [array[i]]);
2025        } catch(err) {
2026          throw err;
2027        }
2028        lines.push(l);
2029      }
2030      return new ZOO.Geometry.MultiLineString(lines);
2031    },
2032    /**
2033     * Method: parseCoords.polygon
2034     * Convert a coordinate array from GeoJSON into an
2035     *     <ZOO.Geometry.Polygon>.
2036     *
2037     * Parameters:
2038     * array - {Object} The coordinates array from the GeoJSON fragment.
2039     *
2040     * Returns:
2041     * {<ZOO.Geometry.Polygon>} A geometry.
2042     */
2043    "polygon": function(array) {
2044      var rings = [];
2045      var r, l;
2046      for(var i=0, len=array.length; i<len; ++i) {
2047        try {
2048          l = this.parseCoords["linestring"].apply(this, [array[i]]);
2049        } catch(err) {
2050          throw err;
2051        }
2052        r = new ZOO.Geometry.LinearRing(l.components);
2053        rings.push(r);
2054      }
2055      return new ZOO.Geometry.Polygon(rings);
2056    },
2057    /**
2058     * Method: parseCoords.multipolygon
2059     * Convert a coordinate array from GeoJSON into an
2060     *     <ZOO.Geometry.MultiPolygon>.
2061     *
2062     * Parameters:
2063     * array - {Object} The coordinates array from the GeoJSON fragment.
2064     *
2065     * Returns:
2066     * {<ZOO.Geometry.MultiPolygon>} A geometry.
2067     */
2068    "multipolygon": function(array) {
2069      var polys = [];
2070      var p = null;
2071      for(var i=0, len=array.length; i<len; ++i) {
2072        try {
2073          p = this.parseCoords["polygon"].apply(this, [array[i]]);
2074        } catch(err) {
2075          throw err;
2076        }
2077        polys.push(p);
2078      }
2079      return new ZOO.Geometry.MultiPolygon(polys);
2080    },
2081    /**
2082     * Method: parseCoords.box
2083     * Convert a coordinate array from GeoJSON into an
2084     *     <ZOO.Geometry.Polygon>.
2085     *
2086     * Parameters:
2087     * array - {Object} The coordinates array from the GeoJSON fragment.
2088     *
2089     * Returns:
2090     * {<ZOO.Geometry.Polygon>} A geometry.
2091     */
2092    "box": function(array) {
2093      if(array.length != 2) {
2094        throw "GeoJSON box coordinates must have 2 elements";
2095      }
2096      return new ZOO.Geometry.Polygon([
2097          new ZOO.Geometry.LinearRing([
2098            new ZOO.Geometry.Point(array[0][0], array[0][1]),
2099            new ZOO.Geometry.Point(array[1][0], array[0][1]),
2100            new ZOO.Geometry.Point(array[1][0], array[1][1]),
2101            new ZOO.Geometry.Point(array[0][0], array[1][1]),
2102            new Z0O.Geometry.Point(array[0][0], array[0][1])
2103          ])
2104      ]);
2105    }
2106  },
2107  /**
2108   * Method: write
2109   * Serialize a feature, geometry, array of features into a GeoJSON string.
2110   *
2111   * Parameters:
2112   * obj - {Object} An <ZOO.Feature>, <ZOO.Geometry>,
2113   *     or an array of features.
2114   * pretty - {Boolean} Structure the output with newlines and indentation.
2115   *     Default is false.
2116   *
2117   * Returns:
2118   * {String} The GeoJSON string representation of the input geometry,
2119   *     features, or array of features.
2120   */
2121  write: function(obj, pretty) {
2122    var geojson = {
2123      "type": null
2124    };
2125    if(obj instanceof Array) {
2126      geojson.type = "FeatureCollection";
2127      var numFeatures = obj.length;
2128      geojson.features = new Array(numFeatures);
2129      for(var i=0; i<numFeatures; ++i) {
2130        var element = obj[i];
2131        if(!element instanceof ZOO.Feature) {
2132          var msg = "FeatureCollection only supports collections " +
2133            "of features: " + element;
2134          throw msg;
2135        }
2136        geojson.features[i] = this.extract.feature.apply(this, [element]);
2137      }
2138    } else if (obj.CLASS_NAME.indexOf("ZOO.Geometry") == 0) {
2139      geojson = this.extract.geometry.apply(this, [obj]);
2140    } else if (obj instanceof ZOO.Feature) {
2141      geojson = this.extract.feature.apply(this, [obj]);
2142      /*
2143      if(obj.layer && obj.layer.projection) {
2144        geojson.crs = this.createCRSObject(obj);
2145      }
2146      */
2147    }
2148    return ZOO.Format.JSON.prototype.write.apply(this,
2149                                                 [geojson, pretty]);
2150  },
2151  /**
2152   * Method: createCRSObject
2153   * Create the CRS object for an object.
2154   *
2155   * Parameters:
2156   * object - {<ZOO.Feature>}
2157   *
2158   * Returns:
2159   * {Object} An object which can be assigned to the crs property
2160   * of a GeoJSON object.
2161   */
2162  createCRSObject: function(object) {
2163    //var proj = object.layer.projection.toString();
2164    var proj = object.projection.toString();
2165    var crs = {};
2166    if (proj.match(/epsg:/i)) {
2167      var code = parseInt(proj.substring(proj.indexOf(":") + 1));
2168      if (code == 4326) {
2169        crs = {
2170          "type": "OGC",
2171          "properties": {
2172            "urn": "urn:ogc:def:crs:OGC:1.3:CRS84"
2173          }
2174        };
2175      } else {   
2176        crs = {
2177          "type": "EPSG",
2178          "properties": {
2179            "code": code 
2180          }
2181        };
2182      }   
2183    }
2184    return crs;
2185  },
2186  /**
2187   * Property: extract
2188   * Object with properties corresponding to the GeoJSON types.
2189   *     Property values are functions that do the actual value extraction.
2190   */
2191  extract: {
2192    /**
2193     * Method: extract.feature
2194     * Return a partial GeoJSON object representing a single feature.
2195     *
2196     * Parameters:
2197     * feature - {<ZOO.Feature>}
2198     *
2199     * Returns:
2200     * {Object} An object representing the point.
2201     */
2202    'feature': function(feature) {
2203      var geom = this.extract.geometry.apply(this, [feature.geometry]);
2204      return {
2205        "type": "Feature",
2206        "id": feature.fid == null ? feature.id : feature.fid,
2207        "properties": feature.attributes,
2208        "geometry": geom
2209      };
2210    },
2211    /**
2212     * Method: extract.geometry
2213     * Return a GeoJSON object representing a single geometry.
2214     *
2215     * Parameters:
2216     * geometry - {<ZOO.Geometry>}
2217     *
2218     * Returns:
2219     * {Object} An object representing the geometry.
2220     */
2221    'geometry': function(geometry) {
2222      if (geometry == null)
2223        return null;
2224      if (this.internalProjection && this.externalProjection) {
2225        geometry = geometry.clone();
2226        geometry.transform(this.internalProjection, 
2227            this.externalProjection);
2228      }                       
2229      var geometryType = geometry.CLASS_NAME.split('.')[2];
2230      var data = this.extract[geometryType.toLowerCase()].apply(this, [geometry]);
2231      var json;
2232      if(geometryType == "Collection")
2233        json = {
2234          "type": "GeometryCollection",
2235          "geometries": data
2236        };
2237      else
2238        json = {
2239          "type": geometryType,
2240          "coordinates": data
2241        };
2242      return json;
2243    },
2244    /**
2245     * Method: extract.point
2246     * Return an array of coordinates from a point.
2247     *
2248     * Parameters:
2249     * point - {<ZOO.Geometry.Point>}
2250     *
2251     * Returns:
2252     * {Array} An array of coordinates representing the point.
2253     */
2254    'point': function(point) {
2255      return [point.x, point.y];
2256    },
2257    /**
2258     * Method: extract.multipoint
2259     * Return an array of coordinates from a multipoint.
2260     *
2261     * Parameters:
2262     * multipoint - {<ZOO.Geometry.MultiPoint>}
2263     *
2264     * Returns:
2265     * {Array} An array of point coordinate arrays representing
2266     *     the multipoint.
2267     */
2268    'multipoint': function(multipoint) {
2269      var array = [];
2270      for(var i=0, len=multipoint.components.length; i<len; ++i) {
2271        array.push(this.extract.point.apply(this, [multipoint.components[i]]));
2272      }
2273      return array;
2274    },
2275    /**
2276     * Method: extract.linestring
2277     * Return an array of coordinate arrays from a linestring.
2278     *
2279     * Parameters:
2280     * linestring - {<ZOO.Geometry.LineString>}
2281     *
2282     * Returns:
2283     * {Array} An array of coordinate arrays representing
2284     *     the linestring.
2285     */
2286    'linestring': function(linestring) {
2287      var array = [];
2288      for(var i=0, len=linestring.components.length; i<len; ++i) {
2289        array.push(this.extract.point.apply(this, [linestring.components[i]]));
2290      }
2291      return array;
2292    },
2293    /**
2294     * Method: extract.multilinestring
2295     * Return an array of linestring arrays from a linestring.
2296     *
2297     * Parameters:
2298     * multilinestring - {<ZOO.Geometry.MultiLineString>}
2299     *
2300     * Returns:
2301     * {Array} An array of linestring arrays representing
2302     *     the multilinestring.
2303     */
2304    'multilinestring': function(multilinestring) {
2305      var array = [];
2306      for(var i=0, len=multilinestring.components.length; i<len; ++i) {
2307        array.push(this.extract.linestring.apply(this, [multilinestring.components[i]]));
2308      }
2309      return array;
2310    },
2311    /**
2312     * Method: extract.polygon
2313     * Return an array of linear ring arrays from a polygon.
2314     *
2315     * Parameters:
2316     * polygon - {<ZOO.Geometry.Polygon>}
2317     *
2318     * Returns:
2319     * {Array} An array of linear ring arrays representing the polygon.
2320     */
2321    'polygon': function(polygon) {
2322      var array = [];
2323      for(var i=0, len=polygon.components.length; i<len; ++i) {
2324        array.push(this.extract.linestring.apply(this, [polygon.components[i]]));
2325      }
2326      return array;
2327    },
2328    /**
2329     * Method: extract.multipolygon
2330     * Return an array of polygon arrays from a multipolygon.
2331     *
2332     * Parameters:
2333     * multipolygon - {<ZOO.Geometry.MultiPolygon>}
2334     *
2335     * Returns:
2336     * {Array} An array of polygon arrays representing
2337     *     the multipolygon
2338     */
2339    'multipolygon': function(multipolygon) {
2340      var array = [];
2341      for(var i=0, len=multipolygon.components.length; i<len; ++i) {
2342        array.push(this.extract.polygon.apply(this, [multipolygon.components[i]]));
2343      }
2344      return array;
2345    },
2346    /**
2347     * Method: extract.collection
2348     * Return an array of geometries from a geometry collection.
2349     *
2350     * Parameters:
2351     * collection - {<ZOO.Geometry.Collection>}
2352     *
2353     * Returns:
2354     * {Array} An array of geometry objects representing the geometry
2355     *     collection.
2356     */
2357    'collection': function(collection) {
2358      var len = collection.components.length;
2359      var array = new Array(len);
2360      for(var i=0; i<len; ++i) {
2361        array[i] = this.extract.geometry.apply(
2362            this, [collection.components[i]]
2363            );
2364      }
2365      return array;
2366    }
2367  },
2368  CLASS_NAME: 'ZOO.Format.GeoJSON'
2369});
2370/**
2371 * Class: ZOO.Format.KML
2372 * Read/Write KML. Create a new instance with the <ZOO.Format.KML>
2373 *     constructor.
2374 *
2375 * Inherits from:
2376 *  - <ZOO.Format>
2377 */
2378ZOO.Format.KML = ZOO.Class(ZOO.Format, {
2379  /**
2380   * Property: kmlns
2381   * {String} KML Namespace to use. Defaults to 2.2 namespace.
2382   */
2383  kmlns: "http://www.opengis.net/kml/2.2",
2384  /**
2385   * Property: foldersName
2386   * {String} Name of the folders.  Default is "ZOO export".
2387   *          If set to null, no name element will be created.
2388   */
2389  foldersName: "ZOO export",
2390  /**
2391   * Property: foldersDesc
2392   * {String} Description of the folders. Default is "Exported on [date]."
2393   *          If set to null, no description element will be created.
2394   */
2395  foldersDesc: "Created on " + new Date(),
2396  /**
2397   * Property: placemarksDesc
2398   * {String} Name of the placemarks.  Default is "No description available".
2399   */
2400  placemarksDesc: "No description available",
2401  /**
2402   * Property: extractAttributes
2403   * {Boolean} Extract attributes from KML.  Default is true.
2404   *           Extracting styleUrls requires this to be set to true
2405   */
2406  extractAttributes: true,
2407  /**
2408   * Constructor: ZOO.Format.KML
2409   * Create a new parser for KML.
2410   *
2411   * Parameters:
2412   * options - {Object} An optional object whose properties will be set on
2413   *     this instance.
2414   */
2415  initialize: function(options) {
2416    // compile regular expressions once instead of every time they are used
2417    this.regExes = {
2418           trimSpace: (/^\s*|\s*$/g),
2419           removeSpace: (/\s*/g),
2420           splitSpace: (/\s+/),
2421           trimComma: (/\s*,\s*/g),
2422           kmlColor: (/(\w{2})(\w{2})(\w{2})(\w{2})/),
2423           kmlIconPalette: (/root:\/\/icons\/palette-(\d+)(\.\w+)/),
2424           straightBracket: (/\$\[(.*?)\]/g)
2425    };
2426    // KML coordinates are always in longlat WGS84
2427    this.externalProjection = new ZOO.Projection("EPSG:4326");
2428    ZOO.Format.prototype.initialize.apply(this, [options]);
2429  },
2430  /**
2431   * APIMethod: read
2432   * Read data from a string, and return a list of features.
2433   *
2434   * Parameters:
2435   * data    - {String} data to read/parse.
2436   *
2437   * Returns:
2438   * {Array(<ZOO.Feature>)} List of features.
2439   */
2440  read: function(data) {
2441    this.features = [];
2442    data = data.replace(/^<\?xml\s+version\s*=\s*(["'])[^\1]+\1[^?]*\?>/, "");
2443    data = new XML(data);
2444    var placemarks = data..*::Placemark;
2445    this.parseFeatures(placemarks);
2446    return this.features;
2447  },
2448  /**
2449   * Method: parseFeatures
2450   * Loop through all Placemark nodes and parse them.
2451   * Will create a list of features
2452   *
2453   * Parameters:
2454   * nodes    - {Array} of {E4XElement} data to read/parse.
2455   * options  - {Object} Hash of options
2456   *
2457   */
2458  parseFeatures: function(nodes) {
2459    var features = new Array(nodes.length());
2460    for(var i=0, len=nodes.length(); i<len; i++) {
2461      var featureNode = nodes[i];
2462      var feature = this.parseFeature.apply(this,[featureNode]) ;
2463      features[i] = feature;
2464    }
2465    this.features = this.features.concat(features);
2466  },
2467  /**
2468   * Method: parseFeature
2469   * This function is the core of the KML parsing code in ZOO.
2470   *     It creates the geometries that are then attached to the returned
2471   *     feature, and calls parseAttributes() to get attribute data out.
2472   *
2473   * Parameters:
2474   * node - {E4XElement}
2475   *
2476   * Returns:
2477   * {<ZOO.Feature>} A vector feature.
2478   */
2479  parseFeature: function(node) {
2480    // only accept one geometry per feature - look for highest "order"
2481    var order = ["MultiGeometry", "Polygon", "LineString", "Point"];
2482    var type, nodeList, geometry, parser;
2483    for(var i=0, len=order.length; i<len; ++i) {
2484      type = order[i];
2485      nodeList = node.descendants(QName(null,type));
2486      if (nodeList.length()> 0) {
2487        var parser = this.parseGeometry[type.toLowerCase()];
2488        if(parser) {
2489          geometry = parser.apply(this, [nodeList[0]]);
2490          if (this.internalProjection && this.externalProjection) {
2491            geometry.transform(this.externalProjection, 
2492                               this.internalProjection); 
2493          }                       
2494        }
2495        // stop looking for different geometry types
2496        break;
2497      }
2498    }
2499    // construct feature (optionally with attributes)
2500    var attributes;
2501    if(this.extractAttributes) {
2502      attributes = this.parseAttributes(node);
2503    }
2504    var feature = new ZOO.Feature(geometry, attributes);
2505    var fid = node.@id || node.@name;
2506    if(fid != null)
2507      feature.fid = fid;
2508    return feature;
2509  },
2510  /**
2511   * Property: parseGeometry
2512   * Properties of this object are the functions that parse geometries based
2513   *     on their type.
2514   */
2515  parseGeometry: {
2516    /**
2517     * Method: parseGeometry.point
2518     * Given a KML node representing a point geometry, create a ZOO
2519     *     point geometry.
2520     *
2521     * Parameters:
2522     * node - {E4XElement} A KML Point node.
2523     *
2524     * Returns:
2525     * {<ZOO.Geometry.Point>} A point geometry.
2526     */
2527    'point': function(node) {
2528      var coordString = node.*::coordinates.toString();
2529      coordString = coordString.replace(this.regExes.removeSpace, "");
2530      coords = coordString.split(",");
2531      var point = null;
2532      if(coords.length > 1) {
2533        // preserve third dimension
2534        if(coords.length == 2) {
2535          coords[2] = null;
2536        }
2537        point = new ZOO.Geometry.Point(coords[0], coords[1], coords[2]);
2538      }
2539      return point;
2540    },
2541    /**
2542     * Method: parseGeometry.linestring
2543     * Given a KML node representing a linestring geometry, create a
2544     *     ZOO linestring geometry.
2545     *
2546     * Parameters:
2547     * node - {E4XElement} A KML LineString node.
2548     *
2549     * Returns:
2550     * {<ZOO.Geometry.LineString>} A linestring geometry.
2551     */
2552    'linestring': function(node, ring) {
2553      var line = null;
2554      var coordString = node.*::coordinates.toString();
2555      coordString = coordString.replace(this.regExes.trimSpace,
2556          "");
2557      coordString = coordString.replace(this.regExes.trimComma,
2558          ",");
2559      var pointList = coordString.split(this.regExes.splitSpace);
2560      var numPoints = pointList.length;
2561      var points = new Array(numPoints);
2562      var coords, numCoords;
2563      for(var i=0; i<numPoints; ++i) {
2564        coords = pointList[i].split(",");
2565        numCoords = coords.length;
2566        if(numCoords > 1) {
2567          if(coords.length == 2) {
2568            coords[2] = null;
2569          }
2570          points[i] = new ZOO.Geometry.Point(coords[0],
2571                                             coords[1],
2572                                             coords[2]);
2573        }
2574      }
2575      if(numPoints) {
2576        if(ring) {
2577          line = new ZOO.Geometry.LinearRing(points);
2578        } else {
2579          line = new ZOO.Geometry.LineString(points);
2580        }
2581      } else {
2582        throw "Bad LineString coordinates: " + coordString;
2583      }
2584      return line;
2585    },
2586    /**
2587     * Method: parseGeometry.polygon
2588     * Given a KML node representing a polygon geometry, create a
2589     *     ZOO polygon geometry.
2590     *
2591     * Parameters:
2592     * node - {E4XElement} A KML Polygon node.
2593     *
2594     * Returns:
2595     * {<ZOO.Geometry.Polygon>} A polygon geometry.
2596     */
2597    'polygon': function(node) {
2598      var nodeList = node..*::LinearRing;
2599      var numRings = nodeList.length();
2600      var components = new Array(numRings);
2601      if(numRings > 0) {
2602        // this assumes exterior ring first, inner rings after
2603        var ring;
2604        for(var i=0, len=nodeList.length(); i<len; ++i) {
2605          ring = this.parseGeometry.linestring.apply(this,
2606                                                     [nodeList[i], true]);
2607          if(ring) {
2608            components[i] = ring;
2609          } else {
2610            throw "Bad LinearRing geometry: " + i;
2611          }
2612        }
2613      }
2614      return new ZOO.Geometry.Polygon(components);
2615    },
2616    /**
2617     * Method: parseGeometry.multigeometry
2618     * Given a KML node representing a multigeometry, create a
2619     *     ZOO geometry collection.
2620     *
2621     * Parameters:
2622     * node - {E4XElement} A KML MultiGeometry node.
2623     *
2624     * Returns:
2625     * {<ZOO.Geometry.Collection>} A geometry collection.
2626     */
2627    'multigeometry': function(node) {
2628      var child, parser;
2629      var parts = [];
2630      var children = node.*::*;
2631      for(var i=0, len=children.length(); i<len; ++i ) {
2632        child = children[i];
2633        var type = child.localName();
2634        var parser = this.parseGeometry[type.toLowerCase()];
2635        if(parser) {
2636          parts.push(parser.apply(this, [child]));
2637        }
2638      }
2639      return new ZOO.Geometry.Collection(parts);
2640    }
2641  },
2642  /**
2643   * Method: parseAttributes
2644   *
2645   * Parameters:
2646   * node - {E4XElement}
2647   *
2648   * Returns:
2649   * {Object} An attributes object.
2650   */
2651  parseAttributes: function(node) {
2652    var attributes = {};
2653    var edNodes = node.*::ExtendedData;
2654    if (edNodes.length() > 0) {
2655      attributes = this.parseExtendedData(edNodes[0])
2656    }
2657    var child, grandchildren;
2658    var children = node.*::*;
2659    for(var i=0, len=children.length(); i<len; ++i) {
2660      child = children[i];
2661      grandchildren = child..*::*;
2662      if(grandchildren.length() == 1) {
2663        var name = child.localName();
2664        var value = child.toString();
2665        if (value) {
2666          value = value.replace(this.regExes.trimSpace, "");
2667          attributes[name] = value;
2668        }
2669      }
2670    }
2671    return attributes;
2672  },
2673  /**
2674   * Method: parseExtendedData
2675   * Parse ExtendedData from KML. Limited support for schemas/datatypes.
2676   *     See http://code.google.com/apis/kml/documentation/kmlreference.html#extendeddata
2677   *     for more information on extendeddata.
2678   *
2679   * Parameters:
2680   * node - {E4XElement}
2681   *
2682   * Returns:
2683   * {Object} An attributes object.
2684   */
2685  parseExtendedData: function(node) {
2686    var attributes = {};
2687    var dataNodes = node.*::Data;
2688    for (var i = 0, len = dataNodes.length(); i < len; i++) {
2689      var data = dataNodes[i];
2690      var key = data.@name;
2691      var ed = {};
2692      var valueNode = data.*::value;
2693      if (valueNode.length() > 0)
2694        ed['value'] = valueNode[0].toString();
2695      var nameNode = data.*::displayName;
2696      if (nameNode.length() > 0)
2697        ed['displayName'] = valueNode[0].toString();
2698      attributes[key] = ed;
2699    }
2700    return attributes;
2701  },
2702  /**
2703   * Method: write
2704   * Accept Feature Collection, and return a string.
2705   *
2706   * Parameters:
2707   * features - {Array(<ZOO.Feature>} An array of features.
2708   *
2709   * Returns:
2710   * {String} A KML string.
2711   */
2712  write: function(features) {
2713    if(!(features instanceof Array))
2714      features = [features];
2715    var kml = new XML('<kml xmlns="'+this.kmlns+'"></kml>');
2716    var folder = kml.Document.Folder;
2717    folder.name = this.foldersName;
2718    folder.description = this.foldersDesc;
2719    for(var i=0, len=features.length; i<len; ++i) {
2720      folder.Placemark[i] = this.createPlacemark(features[i]);
2721    }
2722    return kml.toXMLString();
2723  },
2724  /**
2725   * Method: createPlacemark
2726   * Creates and returns a KML placemark node representing the given feature.
2727   *
2728   * Parameters:
2729   * feature - {<ZOO.Feature>}
2730   *
2731   * Returns:
2732   * {E4XElement}
2733   */
2734  createPlacemark: function(feature) {
2735    var placemark = new XML('<Placemark xmlns="'+this.kmlns+'"></Placemark>');
2736    placemark.name = (feature.attributes.name) ?
2737                    feature.attributes.name : feature.id;
2738    placemark.description = (feature.attributes.description) ?
2739                             feature.attributes.description : this.placemarksDesc;
2740    if(feature.fid != null)
2741      placemark.@id = feature.fid;
2742    placemark.*[2] = this.buildGeometryNode(feature.geometry);
2743    return placemark;
2744  },
2745  /**
2746   * Method: buildGeometryNode
2747   * Builds and returns a KML geometry node with the given geometry.
2748   *
2749   * Parameters:
2750   * geometry - {<ZOO.Geometry>}
2751   *
2752   * Returns:
2753   * {E4XElement}
2754   */
2755  buildGeometryNode: function(geometry) {
2756    if (this.internalProjection && this.externalProjection) {
2757      geometry = geometry.clone();
2758      geometry.transform(this.internalProjection, 
2759                         this.externalProjection);
2760    }
2761    var className = geometry.CLASS_NAME;
2762    var type = className.substring(className.lastIndexOf(".") + 1);
2763    var builder = this.buildGeometry[type.toLowerCase()];
2764    var node = null;
2765    if(builder) {
2766      node = builder.apply(this, [geometry]);
2767    }
2768    return node;
2769  },
2770  /**
2771   * Property: buildGeometry
2772   * Object containing methods to do the actual geometry node building
2773   *     based on geometry type.
2774   */
2775  buildGeometry: {
2776    /**
2777     * Method: buildGeometry.point
2778     * Given a ZOO point geometry, create a KML point.
2779     *
2780     * Parameters:
2781     * geometry - {<ZOO.Geometry.Point>} A point geometry.
2782     *
2783     * Returns:
2784     * {E4XElement} A KML point node.
2785     */
2786    'point': function(geometry) {
2787      var kml = new XML('<Point xmlns="'+this.kmlns+'"></Point>');
2788      kml.coordinates = this.buildCoordinatesNode(geometry);
2789      return kml;
2790    },
2791    /**
2792     * Method: buildGeometry.multipoint
2793     * Given a ZOO multipoint geometry, create a KML
2794     *     GeometryCollection.
2795     *
2796     * Parameters:
2797     * geometry - {<ZOO.Geometry.MultiPoint>} A multipoint geometry.
2798     *
2799     * Returns:
2800     * {E4XElement} A KML GeometryCollection node.
2801     */
2802    'multipoint': function(geometry) {
2803      return this.buildGeometry.collection.apply(this, [geometry]);
2804    },
2805    /**
2806     * Method: buildGeometry.linestring
2807     * Given a ZOO linestring geometry, create a KML linestring.
2808     *
2809     * Parameters:
2810     * geometry - {<ZOO.Geometry.LineString>} A linestring geometry.
2811     *
2812     * Returns:
2813     * {E4XElement} A KML linestring node.
2814     */
2815    'linestring': function(geometry) {
2816      var kml = new XML('<LineString xmlns="'+this.kmlns+'"></LineString>');
2817      kml.coordinates = this.buildCoordinatesNode(geometry);
2818      return kml;
2819    },
2820    /**
2821     * Method: buildGeometry.multilinestring
2822     * Given a ZOO multilinestring geometry, create a KML
2823     *     GeometryCollection.
2824     *
2825     * Parameters:
2826     * geometry - {<ZOO.Geometry.MultiLineString>} A multilinestring geometry.
2827     *
2828     * Returns:
2829     * {E4XElement} A KML GeometryCollection node.
2830     */
2831    'multilinestring': function(geometry) {
2832      return this.buildGeometry.collection.apply(this, [geometry]);
2833    },
2834    /**
2835     * Method: buildGeometry.linearring
2836     * Given a ZOO linearring geometry, create a KML linearring.
2837     *
2838     * Parameters:
2839     * geometry - {<ZOO.Geometry.LinearRing>} A linearring geometry.
2840     *
2841     * Returns:
2842     * {E4XElement} A KML linearring node.
2843     */
2844    'linearring': function(geometry) {
2845      var kml = new XML('<LinearRing xmlns="'+this.kmlns+'"></LinearRing>');
2846      kml.coordinates = this.buildCoordinatesNode(geometry);
2847      return kml;
2848    },
2849    /**
2850     * Method: buildGeometry.polygon
2851     * Given a ZOO polygon geometry, create a KML polygon.
2852     *
2853     * Parameters:
2854     * geometry - {<ZOO.Geometry.Polygon>} A polygon geometry.
2855     *
2856     * Returns:
2857     * {E4XElement} A KML polygon node.
2858     */
2859    'polygon': function(geometry) {
2860      var kml = new XML('<Polygon xmlns="'+this.kmlns+'"></Polygon>');
2861      var rings = geometry.components;
2862      var ringMember, ringGeom, type;
2863      for(var i=0, len=rings.length; i<len; ++i) {
2864        type = (i==0) ? "outerBoundaryIs" : "innerBoundaryIs";
2865        ringMember = new XML('<'+type+' xmlns="'+this.kmlns+'"></'+type+'>');
2866        ringMember.LinearRing = this.buildGeometry.linearring.apply(this,[rings[i]]);
2867        kml.*[i] = ringMember;
2868      }
2869      return kml;
2870    },
2871    /**
2872     * Method: buildGeometry.multipolygon
2873     * Given a ZOO multipolygon geometry, create a KML
2874     *     GeometryCollection.
2875     *
2876     * Parameters:
2877     * geometry - {<ZOO.Geometry.Point>} A multipolygon geometry.
2878     *
2879     * Returns:
2880     * {E4XElement} A KML GeometryCollection node.
2881     */
2882    'multipolygon': function(geometry) {
2883      return this.buildGeometry.collection.apply(this, [geometry]);
2884    },
2885    /**
2886     * Method: buildGeometry.collection
2887     * Given a ZOO geometry collection, create a KML MultiGeometry.
2888     *
2889     * Parameters:
2890     * geometry - {<ZOO.Geometry.Collection>} A geometry collection.
2891     *
2892     * Returns:
2893     * {E4XElement} A KML MultiGeometry node.
2894     */
2895    'collection': function(geometry) {
2896      var kml = new XML('<MultiGeometry xmlns="'+this.kmlns+'"></MultiGeometry>');
2897      var child;
2898      for(var i=0, len=geometry.components.length; i<len; ++i) {
2899        kml.*[i] = this.buildGeometryNode.apply(this,[geometry.components[i]]);
2900      }
2901      return kml;
2902    }
2903  },
2904  /**
2905   * Method: buildCoordinatesNode
2906   * Builds and returns the KML coordinates node with the given geometry
2907   *     <coordinates>...</coordinates>
2908   *
2909   * Parameters:
2910   * geometry - {<ZOO.Geometry>}
2911   *
2912   * Return:
2913   * {E4XElement}
2914   */
2915  buildCoordinatesNode: function(geometry) {
2916    var cooridnates = new XML('<coordinates xmlns="'+this.kmlns+'"></coordinates>');
2917    var points = geometry.components;
2918    if(points) {
2919      // LineString or LinearRing
2920      var point;
2921      var numPoints = points.length;
2922      var parts = new Array(numPoints);
2923      for(var i=0; i<numPoints; ++i) {
2924        point = points[i];
2925        parts[i] = point.x + "," + point.y;
2926      }
2927      coordinates = parts.join(" ");
2928    } else {
2929      // Point
2930      coordinates = geometry.x + "," + geometry.y;
2931    }
2932    return coordinates;
2933  },
2934  CLASS_NAME: 'ZOO.Format.KML'
2935});
2936/**
2937 * Class: ZOO.Format.GML
2938 * Read/Write GML. Create a new instance with the <ZOO.Format.GML>
2939 *     constructor.  Supports the GML simple features profile.
2940 *
2941 * Inherits from:
2942 *  - <ZOO.Format>
2943 */
2944ZOO.Format.GML = ZOO.Class(ZOO.Format, {
2945  /**
2946   * Property: schemaLocation
2947   * {String} Schema location for a particular minor version.
2948   */
2949  schemaLocation: "http://www.opengis.net/gml http://schemas.opengis.net/gml/2.1.2/feature.xsd",
2950  /**
2951   * Property: namespaces
2952   * {Object} Mapping of namespace aliases to namespace URIs.
2953   */
2954  namespaces: {
2955    ogr: "http://ogr.maptools.org/",
2956    gml: "http://www.opengis.net/gml",
2957    xlink: "http://www.w3.org/1999/xlink",
2958    xsi: "http://www.w3.org/2001/XMLSchema-instance",
2959    wfs: "http://www.opengis.net/wfs" // this is a convenience for reading wfs:FeatureCollection
2960  },
2961  /**
2962   * Property: defaultPrefix
2963   */
2964  defaultPrefix: 'ogr',
2965  /**
2966   * Property: collectionName
2967   * {String} Name of featureCollection element.
2968   */
2969  collectionName: "FeatureCollection",
2970  /*
2971   * Property: featureName
2972   * {String} Element name for features. Default is "sql_statement".
2973   */
2974  featureName: "sql_statement",
2975  /**
2976   * Property: geometryName
2977   * {String} Name of geometry element.  Defaults to "geometryProperty".
2978   */
2979  geometryName: "geometryProperty",
2980  /**
2981   * Property: xy
2982   * {Boolean} Order of the GML coordinate true:(x,y) or false:(y,x)
2983   * Changing is not recommended, a new Format should be instantiated.
2984   */
2985  xy: true,
2986  /**
2987   * Property: extractAttributes
2988   * {Boolean} Could we extract attributes
2989   */
2990  extractAttributes: true,
2991  /**
2992   * Constructor: ZOO.Format.GML
2993   * Create a new parser for GML.
2994   *
2995   * Parameters:
2996   * options - {Object} An optional object whose properties will be set on
2997   *     this instance.
2998   */
2999  initialize: function(options) {
3000    // compile regular expressions once instead of every time they are used
3001    this.regExes = {
3002      trimSpace: (/^\s*|\s*$/g),
3003      removeSpace: (/\s*/g),
3004      splitSpace: (/\s+/),
3005      trimComma: (/\s*,\s*/g)
3006    };
3007    ZOO.Format.prototype.initialize.apply(this, [options]);
3008  },
3009  /**
3010   * Method: read
3011   * Read data from a string, and return a list of features.
3012   *
3013   * Parameters:
3014   * data - {String} data to read/parse.
3015   *
3016   * Returns:
3017   * {Array(<ZOO.Feature>)} An array of features.
3018   */
3019  read: function(data) {
3020    this.features = [];
3021    data = data.replace(/^<\?xml\s+version\s*=\s*(["'])[^\1]+\1[^?]*\?>/, "");
3022    data = new XML(data);
3023
3024    var gmlns = Namespace(this.namespaces['gml']);
3025    var featureNodes = data..gmlns::featureMember;
3026    if (data.localName() == 'featureMember')
3027      featureNodes = data;
3028    var features = [];
3029    for(var i=0,len=featureNodes.length(); i<len; i++) {
3030      var feature = this.parseFeature(featureNodes[i]);
3031      if(feature) {
3032        features.push(feature);
3033      }
3034    }
3035    return features;
3036  },
3037  /**
3038   * Method: parseFeature
3039   * This function is the core of the GML parsing code in ZOO.
3040   *    It creates the geometries that are then attached to the returned
3041   *    feature, and calls parseAttributes() to get attribute data out.
3042   *   
3043   * Parameters:
3044   * node - {E4XElement} A GML feature node.
3045   */
3046  parseFeature: function(node) {
3047    // only accept one geometry per feature - look for highest "order"
3048    var gmlns = Namespace(this.namespaces['gml']);
3049    var order = ["MultiPolygon", "Polygon",
3050                 "MultiLineString", "LineString",
3051                 "MultiPoint", "Point", "Envelope", "Box"];
3052    var type, nodeList, geometry, parser;
3053    for(var i=0; i<order.length; ++i) {
3054      type = order[i];
3055      nodeList = node.descendants(QName(gmlns,type));
3056      if (nodeList.length() > 0) {
3057        var parser = this.parseGeometry[type.toLowerCase()];
3058        if(parser) {
3059          geometry = parser.apply(this, [nodeList[0]]);
3060          if (this.internalProjection && this.externalProjection) {
3061            geometry.transform(this.externalProjection, 
3062                               this.internalProjection); 
3063          }                       
3064        }
3065        // stop looking for different geometry types
3066        break;
3067      }
3068    }
3069    var attributes;
3070    if(this.extractAttributes) {
3071      attributes = this.parseAttributes(node);
3072    }
3073    var feature = new ZOO.Feature(geometry, attributes);
3074    return feature;
3075  },
3076  /**
3077   * Property: parseGeometry
3078   * Properties of this object are the functions that parse geometries based
3079   *     on their type.
3080   */
3081  parseGeometry: {
3082    /**
3083     * Method: parseGeometry.point
3084     * Given a GML node representing a point geometry, create a ZOO
3085     *     point geometry.
3086     *
3087     * Parameters:
3088     * node - {E4XElement} A GML node.
3089     *
3090     * Returns:
3091     * {<ZOO.Geometry.Point>} A point geometry.
3092     */
3093    'point': function(node) {
3094      /**
3095       * Three coordinate variations to consider:
3096       * 1) <gml:pos>x y z</gml:pos>
3097       * 2) <gml:coordinates>x, y, z</gml:coordinates>
3098       * 3) <gml:coord><gml:X>x</gml:X><gml:Y>y</gml:Y></gml:coord>
3099       */
3100      var nodeList, coordString;
3101      var coords = [];
3102      // look for <gml:pos>
3103      var nodeList = node..*::pos;
3104      if(nodeList.length() > 0) {
3105        coordString = nodeList[0].toString();
3106        coordString = coordString.replace(this.regExes.trimSpace, "");
3107        coords = coordString.split(this.regExes.splitSpace);
3108      }
3109      // look for <gml:coordinates>
3110      if(coords.length == 0) {
3111        nodeList = node..*::coordinates;
3112        if(nodeList.length() > 0) {
3113          coordString = nodeList[0].toString();
3114          coordString = coordString.replace(this.regExes.removeSpace,"");
3115          coords = coordString.split(",");
3116        }
3117      }
3118      // look for <gml:coord>
3119      if(coords.length == 0) {
3120        nodeList = node..*::coord;
3121        if(nodeList.length() > 0) {
3122          var xList = nodeList[0].*::X;
3123          var yList = nodeList[0].*::Y;
3124          if(xList.length() > 0 && yList.length() > 0)
3125            coords = [xList[0].toString(),
3126                      yList[0].toString()];
3127        }
3128      }
3129      // preserve third dimension
3130      if(coords.length == 2)
3131        coords[2] = null;
3132      if (this.xy)
3133        return new ZOO.Geometry.Point(coords[0],coords[1],coords[2]);
3134      else
3135        return new ZOO.Geometry.Point(coords[1],coords[0],coords[2]);
3136    },
3137    /**
3138     * Method: parseGeometry.multipoint
3139     * Given a GML node representing a multipoint geometry, create a
3140     *     ZOO multipoint geometry.
3141     *
3142     * Parameters:
3143     * node - {E4XElement} A GML node.
3144     *
3145     * Returns:
3146     * {<ZOO.Geometry.MultiPoint>} A multipoint geometry.
3147     */
3148    'multipoint': function(node) {
3149      var nodeList = node..*::Point;
3150      var components = [];
3151      if(nodeList.length() > 0) {
3152        var point;
3153        for(var i=0, len=nodeList.length(); i<len; ++i) {
3154          point = this.parseGeometry.point.apply(this, [nodeList[i]]);
3155          if(point)
3156            components.push(point);
3157        }
3158      }
3159      return new ZOO.Geometry.MultiPoint(components);
3160    },
3161    /**
3162     * Method: parseGeometry.linestring
3163     * Given a GML node representing a linestring geometry, create a
3164     *     ZOO linestring geometry.
3165     *
3166     * Parameters:
3167     * node - {E4XElement} A GML node.
3168     *
3169     * Returns:
3170     * {<ZOO.Geometry.LineString>} A linestring geometry.
3171     */
3172    'linestring': function(node, ring) {
3173      /**
3174       * Two coordinate variations to consider:
3175       * 1) <gml:posList dimension="d">x0 y0 z0 x1 y1 z1</gml:posList>
3176       * 2) <gml:coordinates>x0, y0, z0 x1, y1, z1</gml:coordinates>
3177       */
3178      var nodeList, coordString;
3179      var coords = [];
3180      var points = [];
3181      // look for <gml:posList>
3182      nodeList = node..*::posList;
3183      if(nodeList.length() > 0) {
3184        coordString = nodeList[0].toString();
3185        coordString = coordString.replace(this.regExes.trimSpace, "");
3186        coords = coordString.split(this.regExes.splitSpace);
3187        var dim = parseInt(nodeList[0].@dimension);
3188        var j, x, y, z;
3189        for(var i=0; i<coords.length/dim; ++i) {
3190          j = i * dim;
3191          x = coords[j];
3192          y = coords[j+1];
3193          z = (dim == 2) ? null : coords[j+2];
3194          if (this.xy)
3195            points.push(new ZOO.Geometry.Point(x, y, z));
3196          else
3197            points.push(new Z0O.Geometry.Point(y, x, z));
3198        }
3199      }
3200      // look for <gml:coordinates>
3201      if(coords.length == 0) {
3202        nodeList = node..*::coordinates;
3203        if(nodeList.length() > 0) {
3204          coordString = nodeList[0].toString();
3205          coordString = coordString.replace(this.regExes.trimSpace,"");
3206          coordString = coordString.replace(this.regExes.trimComma,",");
3207          var pointList = coordString.split(this.regExes.splitSpace);
3208          for(var i=0; i<pointList.length; ++i) {
3209            coords = pointList[i].split(",");
3210            if(coords.length == 2)
3211              coords[2] = null;
3212            if (this.xy)
3213              points.push(new ZOO.Geometry.Point(coords[0],coords[1],coords[2]));
3214            else
3215              points.push(new ZOO.Geometry.Point(coords[1],coords[0],coords[2]));
3216          }
3217        }
3218      }
3219      var line = null;
3220      if(points.length != 0) {
3221        if(ring)
3222          line = new ZOO.Geometry.LinearRing(points);
3223        else
3224          line = new ZOO.Geometry.LineString(points);
3225      }
3226      return line;
3227    },
3228    /**
3229     * Method: parseGeometry.multilinestring
3230     * Given a GML node representing a multilinestring geometry, create a
3231     *     ZOO multilinestring geometry.
3232     *
3233     * Parameters:
3234     * node - {E4XElement} A GML node.
3235     *
3236     * Returns:
3237     * {<ZOO.Geometry.MultiLineString>} A multilinestring geometry.
3238     */
3239    'multilinestring': function(node) {
3240      var nodeList = node..*::LineString;
3241      var components = [];
3242      if(nodeList.length() > 0) {
3243        var line;
3244        for(var i=0, len=nodeList.length(); i<len; ++i) {
3245          line = this.parseGeometry.linestring.apply(this, [nodeList[i]]);
3246          if(point)
3247            components.push(point);
3248        }
3249      }
3250      return new ZOO.Geometry.MultiLineString(components);
3251    },
3252    /**
3253     * Method: parseGeometry.polygon
3254     * Given a GML node representing a polygon geometry, create a
3255     *     ZOO polygon geometry.
3256     *
3257     * Parameters:
3258     * node - {E4XElement} A GML node.
3259     *
3260     * Returns:
3261     * {<ZOO.Geometry.Polygon>} A polygon geometry.
3262     */
3263    'polygon': function(node) {
3264      nodeList = node..*::LinearRing;
3265      var components = [];
3266      if(nodeList.length() > 0) {
3267        // this assumes exterior ring first, inner rings after
3268        var ring;
3269        for(var i=0, len = nodeList.length(); i<len; ++i) {
3270          ring = this.parseGeometry.linestring.apply(this,[nodeList[i], true]);
3271          if(ring)
3272            components.push(ring);
3273        }
3274      }
3275      return new ZOO.Geometry.Polygon(components);
3276    },
3277    /**
3278     * Method: parseGeometry.multipolygon
3279     * Given a GML node representing a multipolygon geometry, create a
3280     *     ZOO multipolygon geometry.
3281     *
3282     * Parameters:
3283     * node - {E4XElement} A GML node.
3284     *
3285     * Returns:
3286     * {<ZOO.Geometry.MultiPolygon>} A multipolygon geometry.
3287     */
3288    'multipolygon': function(node) {
3289      var nodeList = node..*::Polygon;
3290      var components = [];
3291      if(nodeList.length() > 0) {
3292        var polygon;
3293        for(var i=0, len=nodeList.length(); i<len; ++i) {
3294          polygon = this.parseGeometry.polygon.apply(this, [nodeList[i]]);
3295          if(polygon)
3296            components.push(polygon);
3297        }
3298      }
3299      return new ZOO.Geometry.MultiPolygon(components);
3300    },
3301    /**
3302     * Method: parseGeometry.envelope
3303     * Given a GML node representing an envelope, create a
3304     *     ZOO polygon geometry.
3305     *
3306     * Parameters:
3307     * node - {E4XElement} A GML node.
3308     *
3309     * Returns:
3310     * {<ZOO.Geometry.Polygon>} A polygon geometry.
3311     */
3312    'envelope': function(node) {
3313      var components = [];
3314      var coordString;
3315      var envelope;
3316      var lpoint = node..*::lowerCorner;
3317      if (lpoint.length() > 0) {
3318        var coords = [];
3319        if(lpoint.length() > 0) {
3320          coordString = lpoint[0].toString();
3321          coordString = coordString.replace(this.regExes.trimSpace, "");
3322          coords = coordString.split(this.regExes.splitSpace);
3323        }
3324        if(coords.length == 2)
3325          coords[2] = null;
3326        if (this.xy)
3327          var lowerPoint = new ZOO.Geometry.Point(coords[0], coords[1],coords[2]);
3328        else
3329          var lowerPoint = new ZOO.Geometry.Point(coords[1], coords[0],coords[2]);
3330      }
3331      var upoint = node..*::upperCorner;
3332      if (upoint.length() > 0) {
3333        var coords = [];
3334        if(upoint.length > 0) {
3335          coordString = upoint[0].toString();
3336          coordString = coordString.replace(this.regExes.trimSpace, "");
3337          coords = coordString.split(this.regExes.splitSpace);
3338        }
3339        if(coords.length == 2)
3340          coords[2] = null;
3341        if (this.xy)
3342          var upperPoint = new ZOO.Geometry.Point(coords[0], coords[1],coords[2]);
3343        else
3344          var upperPoint = new ZOO.Geometry.Point(coords[1], coords[0],coords[2]);
3345      }
3346      if (lowerPoint && upperPoint) {
3347        components.push(new ZOO.Geometry.Point(lowerPoint.x, lowerPoint.y));
3348        components.push(new ZOO.Geometry.Point(upperPoint.x, lowerPoint.y));
3349        components.push(new ZOO.Geometry.Point(upperPoint.x, upperPoint.y));
3350        components.push(new ZOO.Geometry.Point(lowerPoint.x, upperPoint.y));
3351        components.push(new ZOO.Geometry.Point(lowerPoint.x, lowerPoint.y));
3352        var ring = new ZOO.Geometry.LinearRing(components);
3353        envelope = new ZOO.Geometry.Polygon([ring]);
3354      }
3355      return envelope;
3356    }
3357  },
3358  /**
3359   * Method: parseAttributes
3360   *
3361   * Parameters:
3362   * node - {<E4XElement>}
3363   *
3364   * Returns:
3365   * {Object} An attributes object.
3366   */
3367  parseAttributes: function(node) {
3368    var attributes = {};
3369    // assume attributes are children of the first type 1 child
3370    var childNode = node.*::*[0];
3371    var child, grandchildren;
3372    var children = childNode.*::*;
3373    for(var i=0, len=children.length(); i<len; ++i) {
3374      child = children[i];
3375      grandchildren = child..*::*;
3376      if(grandchildren.length() == 1) {
3377        var name = child.localName();
3378        var value = child.toString();
3379        if (value) {
3380          value = value.replace(this.regExes.trimSpace, "");
3381          attributes[name] = value;
3382        } else
3383          attributes[name] = null;
3384      }
3385    }
3386    return attributes;
3387  },
3388  /**
3389   * Method: write
3390   * Generate a GML document string given a list of features.
3391   *
3392   * Parameters:
3393   * features - {Array(<ZOO.Feature>)} List of features to
3394   *     serialize into a string.
3395   *
3396   * Returns:
3397   * {String} A string representing the GML document.
3398   */
3399  write: function(features) {
3400    if(!(features instanceof Array)) {
3401      features = [features];
3402    }
3403    var pfx = this.defaultPrefix;
3404    var name = pfx+':'+this.collectionName;
3405    var gml = new XML('<'+name+' xmlns:'+pfx+'="'+this.namespaces[pfx]+'" xmlns:gml="'+this.namespaces['gml']+'" xmlns:xsi="'+this.namespaces['xsi']+'" xsi:schemaLocation="'+this.schemaLocation+'"></'+name+'>');
3406    for(var i=0; i<features.length; i++) {
3407      gml.*::*[i] = this.createFeature(features[i]);
3408    }
3409    return gml.toXMLString();
3410  },
3411  /**
3412   * Method: createFeature
3413   * Accept an ZOO.Feature, and build a GML node for it.
3414   *
3415   * Parameters:
3416   * feature - {<ZOO.Feature>} The feature to be built as GML.
3417   *
3418   * Returns:
3419   * {E4XElement} A node reprensting the feature in GML.
3420   */
3421  createFeature: function(feature) {
3422    var pfx = this.defaultPrefix;
3423    var name = pfx+':'+this.featureName;
3424    var fid = feature.fid || feature.id;
3425    var gml = new XML('<gml:featureMember xmlns:gml="'+this.namespaces['gml']+'"><'+name+' xmlns:'+pfx+'="'+this.namespaces[pfx]+'" fid="'+fid+'"></'+name+'></gml:featureMember>');
3426    var geometry = feature.geometry;
3427    gml.*::*[0].*::* = this.buildGeometryNode(geometry);
3428    for(var attr in feature.attributes) {
3429      var attrNode = new XML('<'+pfx+':'+attr+' xmlns:'+pfx+'="'+this.namespaces[pfx]+'">'+feature.attributes[attr]+'</'+pfx+':'+attr+'>');
3430      gml.*::*[0].appendChild(attrNode);
3431    }
3432    return gml;
3433  },
3434  /**
3435   * Method: buildGeometryNode
3436   *
3437   * Parameters:
3438   * geometry - {<ZOO.Geometry>} The geometry to be built as GML.
3439   *
3440   * Returns:
3441   * {E4XElement} A node reprensting the geometry in GML.
3442   */
3443  buildGeometryNode: function(geometry) {
3444    if (this.externalProjection && this.internalProjection) {
3445      geometry = geometry.clone();
3446      geometry.transform(this.internalProjection, 
3447          this.externalProjection);
3448    }   
3449    var className = geometry.CLASS_NAME;
3450    var type = className.substring(className.lastIndexOf(".") + 1);
3451    var builder = this.buildGeometry[type.toLowerCase()];
3452    var pfx = this.defaultPrefix;
3453    var name = pfx+':'+this.geometryName;
3454    var gml = new XML('<'+name+' xmlns:'+pfx+'="'+this.namespaces[pfx]+'"></'+name+'>');
3455    if (builder)
3456      gml.*::* = builder.apply(this, [geometry]);
3457    return gml;
3458  },
3459  /**
3460   * Property: buildGeometry
3461   * Object containing methods to do the actual geometry node building
3462   *     based on geometry type.
3463   */
3464  buildGeometry: {
3465    /**
3466     * Method: buildGeometry.point
3467     * Given a ZOO point geometry, create a GML point.
3468     *
3469     * Parameters:
3470     * geometry - {<ZOO.Geometry.Point>} A point geometry.
3471     *
3472     * Returns:
3473     * {E4XElement} A GML point node.
3474     */
3475    'point': function(geometry) {
3476      var gml = new XML('<gml:Point xmlns:gml="'+this.namespaces['gml']+'"></gml:Point>');
3477      gml.*::*[0] = this.buildCoordinatesNode(geometry);
3478      return gml;
3479    },
3480    /**
3481     * Method: buildGeometry.multipoint
3482     * Given a ZOO multipoint geometry, create a GML multipoint.
3483     *
3484     * Parameters:
3485     * geometry - {<ZOO.Geometry.MultiPoint>} A multipoint geometry.
3486     *
3487     * Returns:
3488     * {E4XElement} A GML multipoint node.
3489     */
3490    'multipoint': function(geometry) {
3491      var gml = new XML('<gml:MultiPoint xmlns:gml="'+this.namespaces['gml']+'"></gml:MultiPoint>');
3492      var points = geometry.components;
3493      var pointMember;
3494      for(var i=0; i<points.length; i++) { 
3495        pointMember = new XML('<gml:pointMember xmlns:gml="'+this.namespaces['gml']+'"></gml:pointMember>');
3496        pointMember.*::* = this.buildGeometry.point.apply(this,[points[i]]);
3497        gml.*::*[i] = pointMember;
3498      }
3499      return gml;           
3500    },
3501    /**
3502     * Method: buildGeometry.linestring
3503     * Given a ZOO linestring geometry, create a GML linestring.
3504     *
3505     * Parameters:
3506     * geometry - {<ZOO.Geometry.LineString>} A linestring geometry.
3507     *
3508     * Returns:
3509     * {E4XElement} A GML linestring node.
3510     */
3511    'linestring': function(geometry) {
3512      var gml = new XML('<gml:LineString xmlns:gml="'+this.namespaces['gml']+'"></gml:LineString>');
3513      gml.*::*[0] = this.buildCoordinatesNode(geometry);
3514      return gml;
3515    },
3516    /**
3517     * Method: buildGeometry.multilinestring
3518     * Given a ZOO multilinestring geometry, create a GML
3519     *     multilinestring.
3520     *
3521     * Parameters:
3522     * geometry - {<ZOO.Geometry.MultiLineString>} A multilinestring
3523     *     geometry.
3524     *
3525     * Returns:
3526     * {E4XElement} A GML multilinestring node.
3527     */
3528    'multilinestring': function(geometry) {
3529      var gml = new XML('<gml:MultiLineString xmlns:gml="'+this.namespaces['gml']+'"></gml:MultiLineString>');
3530      var lines = geometry.components;
3531      var lineMember;
3532      for(var i=0; i<lines.length; i++) { 
3533        lineMember = new XML('<gml:lineStringMember xmlns:gml="'+this.namespaces['gml']+'"></gml:lineStringMember>');
3534        lineMember.*::* = this.buildGeometry.linestring.apply(this,[lines[i]]);
3535        gml.*::*[i] = lineMember;
3536      }
3537      return gml;           
3538    },
3539    /**
3540     * Method: buildGeometry.linearring
3541     * Given a ZOO linearring geometry, create a GML linearring.
3542     *
3543     * Parameters:
3544     * geometry - {<ZOO.Geometry.LinearRing>} A linearring geometry.
3545     *
3546     * Returns:
3547     * {E4XElement} A GML linearring node.
3548     */
3549    'linearring': function(geometry) {
3550      var gml = new XML('<gml:LinearRing xmlns:gml="'+this.namespaces['gml']+'"></gml:LinearRing>');
3551      gml.*::*[0] = this.buildCoordinatesNode(geometry);
3552      return gml;
3553    },
3554    /**
3555     * Method: buildGeometry.polygon
3556     * Given an ZOO polygon geometry, create a GML polygon.
3557     *
3558     * Parameters:
3559     * geometry - {<ZOO.Geometry.Polygon>} A polygon geometry.
3560     *
3561     * Returns:
3562     * {E4XElement} A GML polygon node.
3563     */
3564    'polygon': function(geometry) {
3565      var gml = new XML('<gml:Polygon xmlns:gml="'+this.namespaces['gml']+'"></gml:Polygon>');
3566      var rings = geometry.components;
3567      var ringMember, type;
3568      for(var i=0; i<rings.length; ++i) {
3569        type = (i==0) ? "outerBoundaryIs" : "innerBoundaryIs";
3570        var ringMember = new XML('<gml:'+type+' xmlns:gml="'+this.namespaces['gml']+'"></gml:'+type+'>');
3571        ringMember.*::* = this.buildGeometry.linearring.apply(this,[rings[i]]);
3572        gml.*::*[i] = ringMember;
3573      }
3574      return gml;
3575    },
3576    /**
3577     * Method: buildGeometry.multipolygon
3578     * Given a ZOO multipolygon geometry, create a GML multipolygon.
3579     *
3580     * Parameters:
3581     * geometry - {<ZOO.Geometry.MultiPolygon>} A multipolygon
3582     *     geometry.
3583     *
3584     * Returns:
3585     * {E4XElement} A GML multipolygon node.
3586     */
3587    'multipolygon': function(geometry) {
3588      var gml = new XML('<gml:MultiPolygon xmlns:gml="'+this.namespaces['gml']+'"></gml:MultiPolygon>');
3589      var polys = geometry.components;
3590      var polyMember;
3591      for(var i=0; i<polys.length; i++) { 
3592        polyMember = new XML('<gml:polygonMember xmlns:gml="'+this.namespaces['gml']+'"></gml:polygonMember>');
3593        polyMember.*::* = this.buildGeometry.polygon.apply(this,[polys[i]]);
3594        gml.*::*[i] = polyMember;
3595      }
3596      return gml;           
3597    }
3598  },
3599  /**
3600   * Method: buildCoordinatesNode
3601   * builds the coordinates XmlNode
3602   * (code)
3603   * <gml:coordinates decimal="." cs="," ts=" ">...</gml:coordinates>
3604   * (end)
3605   * Parameters:
3606   * geometry - {<ZOO.Geometry>}
3607   *
3608   * Returns:
3609   * {E4XElement} created E4XElement
3610   */
3611  buildCoordinatesNode: function(geometry) {
3612    var parts = [];
3613    if(geometry instanceof ZOO.Bounds){
3614      parts.push(geometry.left + "," + geometry.bottom);
3615      parts.push(geometry.right + "," + geometry.top);
3616    } else {
3617      var points = (geometry.components) ? geometry.components : [geometry];
3618      for(var i=0; i<points.length; i++) {
3619        parts.push(points[i].x + "," + points[i].y);               
3620      }           
3621    }
3622    return new XML('<gml:coordinates xmlns:gml="'+this.namespaces['gml']+'" decimal="." cs=", " ts=" ">'+parts.join(" ")+'</gml:coordinates>');
3623  },
3624  CLASS_NAME: 'ZOO.Format.GML'
3625});
3626/**
3627 * Class: ZOO.Format.WPS
3628 * Read/Write WPS. Create a new instance with the <ZOO.Format.WPS>
3629 *     constructor. Supports only parseExecuteResponse.
3630 *
3631 * Inherits from:
3632 *  - <ZOO.Format>
3633 */
3634ZOO.Format.WPS = ZOO.Class(ZOO.Format, {
3635  /**
3636   * Property: schemaLocation
3637   * {String} Schema location for a particular minor version.
3638   */
3639  schemaLocation: "http://www.opengis.net/wps/1.0.0/../wpsExecute_request.xsd",
3640  /**
3641   * Property: namespaces
3642   * {Object} Mapping of namespace aliases to namespace URIs.
3643   */
3644  namespaces: {
3645    ows: "http://www.opengis.net/ows/1.1",
3646    wps: "http://www.opengis.net/wps/1.0.0",
3647    xlink: "http://www.w3.org/1999/xlink",
3648    xsi: "http://www.w3.org/2001/XMLSchema-instance",
3649  },
3650  /**
3651   * Method: read
3652   *
3653   * Parameters:
3654   * data - {String} A WPS xml document
3655   *
3656   * Returns:
3657   * {Object} Execute response.
3658   */
3659  read:function(data) {
3660    data = data.replace(/^<\?xml\s+version\s*=\s*(["'])[^\1]+\1[^?]*\?>/, "");
3661    data = new XML(data);
3662    switch (data.localName()) {
3663      case 'ExecuteResponse':
3664        return this.parseExecuteResponse(data);
3665      default:
3666        return null;
3667    }
3668  },
3669  /**
3670   * Method: parseExecuteResponse
3671   *
3672   * Parameters:
3673   * node - {E4XElement} A WPS ExecuteResponse document
3674   *
3675   * Returns:
3676   * {Object} Execute response.
3677   */
3678  parseExecuteResponse: function(node) {
3679    var outputs = node.*::ProcessOutputs.*::Output;
3680    if (outputs.length() > 0) {
3681      var res=[];
3682      for(var i=0;i<outputs.length();i++){
3683        var data = outputs[i].*::Data.*::*[0];
3684        if(!data){
3685          data = outputs[i].*::Reference;
3686        }
3687        var builder = this.parseData[data.localName().toLowerCase()];
3688        if (builder)
3689          res.push(builder.apply(this,[data]));
3690        else
3691          res.push(null);
3692      }
3693      return res.length>1?res:res[0];
3694    } else
3695      return null;
3696  },
3697  /**
3698   * Property: parseData
3699   * Object containing methods to analyse data response.
3700   */
3701  parseData: {
3702    /**
3703     * Method: parseData.complexdata
3704     * Given an Object representing the WPS complex data response.
3705     *
3706     * Parameters:
3707     * node - {E4XElement} A WPS node.
3708     *
3709     * Returns:
3710     * {Object} A WPS complex data response.
3711     */
3712    'complexdata': function(node) {
3713      var result = {value:node.toString()};
3714      if (node.@mimeType.length()>0)
3715        result.mimeType = node.@mimeType;
3716      if (node.@encoding.length()>0)
3717        result.encoding = node.@encoding;
3718      if (node.@schema.length()>0)
3719        result.schema = node.@schema;
3720      return result;
3721    },
3722    /**
3723     * Method: parseData.literaldata
3724     * Given an Object representing the WPS literal data response.
3725     *
3726     * Parameters:
3727     * node - {E4XElement} A WPS node.
3728     *
3729     * Returns:
3730     * {Object} A WPS literal data response.
3731     */
3732    'literaldata': function(node) {
3733      var result = {value:node.toString()};
3734      if (node.@dataType.length()>0)
3735        result.dataType = node.@dataType;
3736      if (node.@uom.length()>0)
3737        result.uom = node.@uom;
3738      return result;
3739    },
3740    /**
3741     * Method: parseData.reference
3742     * Given an Object representing the WPS reference response.
3743     *
3744     * Parameters:
3745     * node - {E4XElement} A WPS node.
3746     *
3747     * Returns:
3748     * {Object} A WPS reference response.
3749     */
3750    'reference': function(node) {
3751      var result = {type:'reference',value:node.@href};
3752      return result;
3753    }
3754  },
3755  CLASS_NAME: 'ZOO.Format.WPS'
3756});
3757
3758/**
3759 * Class: ZOO.Feature
3760 * Vector features use the ZOO.Geometry classes as geometry description.
3761 * They have an 'attributes' property, which is the data object
3762 */
3763ZOO.Feature = ZOO.Class({
3764  /**
3765   * Property: fid
3766   * {String}
3767   */
3768  fid: null,
3769  /**
3770   * Property: geometry
3771   * {<ZOO.Geometry>}
3772   */
3773  geometry: null,
3774  /**
3775   * Property: attributes
3776   * {Object} This object holds arbitrary properties that describe the
3777   *     feature.
3778   */
3779  attributes: null,
3780  /**
3781   * Property: bounds
3782   * {<ZOO.Bounds>} The box bounding that feature's geometry, that
3783   *     property can be set by an <ZOO.Format> object when
3784   *     deserializing the feature, so in most cases it represents an
3785   *     information set by the server.
3786   */
3787  bounds: null,
3788  /**
3789   * Constructor: ZOO.Feature
3790   * Create a vector feature.
3791   *
3792   * Parameters:
3793   * geometry - {<ZOO.Geometry>} The geometry that this feature
3794   *     represents.
3795   * attributes - {Object} An optional object that will be mapped to the
3796   *     <attributes> property.
3797   */
3798  initialize: function(geometry, attributes) {
3799    this.geometry = geometry ? geometry : null;
3800    this.attributes = {};
3801    if (attributes)
3802      this.attributes = ZOO.extend(this.attributes,attributes);
3803  },
3804  /**
3805   * Method: destroy
3806   * nullify references to prevent circular references and memory leaks
3807   */
3808  destroy: function() {
3809    this.geometry = null;
3810  },
3811  /**
3812   * Method: clone
3813   * Create a clone of this vector feature.  Does not set any non-standard
3814   *     properties.
3815   *
3816   * Returns:
3817   * {<ZOO.Feature>} An exact clone of this vector feature.
3818   */
3819  clone: function () {
3820    return new ZOO.Feature(this.geometry ? this.geometry.clone() : null,
3821            this.attributes);
3822  },
3823  /**
3824   * Method: move
3825   * Moves the feature and redraws it at its new location
3826   *
3827   * Parameters:
3828   * x - {Float}
3829   * y - {Float}
3830   */
3831  move: function(x, y) {
3832    if(!this.geometry.move)
3833      return;
3834
3835    this.geometry.move(x,y);
3836    return this.geometry;
3837  },
3838  CLASS_NAME: 'ZOO.Feature'
3839});
3840
3841/**
3842 * Class: ZOO.Geometry
3843 * A Geometry is a description of a geographic object. Create an instance
3844 * of this class with the <ZOO.Geometry> constructor. This is a base class,
3845 * typical geometry types are described by subclasses of this class.
3846 */
3847ZOO.Geometry = ZOO.Class({
3848  /**
3849   * Property: id
3850   * {String} A unique identifier for this geometry.
3851   */
3852  id: null,
3853  /**
3854   * Property: parent
3855   * {<ZOO.Geometry>}This is set when a Geometry is added as component
3856   * of another geometry
3857   */
3858  parent: null,
3859  /**
3860   * Property: bounds
3861   * {<ZOO.Bounds>} The bounds of this geometry
3862   */
3863  bounds: null,
3864  /**
3865   * Constructor: ZOO.Geometry
3866   * Creates a geometry object. 
3867   */
3868  initialize: function() {
3869    //generate unique id
3870  },
3871  /**
3872   * Method: destroy
3873   * Destroy this geometry.
3874   */
3875  destroy: function() {
3876    this.id = null;
3877    this.bounds = null;
3878  },
3879  /**
3880   * Method: clone
3881   * Create a clone of this geometry.  Does not set any non-standard
3882   *     properties of the cloned geometry.
3883   *
3884   * Returns:
3885   * {<ZOO.Geometry>} An exact clone of this geometry.
3886   */
3887  clone: function() {
3888    return new ZOO.Geometry();
3889  },
3890  /**
3891   * Method: extendBounds
3892   * Extend the existing bounds to include the new bounds.
3893   * If geometry's bounds is not yet set, then set a new Bounds.
3894   *
3895   * Parameters:
3896   * newBounds - {<ZOO.Bounds>}
3897   */
3898  extendBounds: function(newBounds){
3899    var bounds = this.getBounds();
3900    if (!bounds)
3901      this.setBounds(newBounds);
3902    else
3903      this.bounds.extend(newBounds);
3904  },
3905  /**
3906   * Set the bounds for this Geometry.
3907   *
3908   * Parameters:
3909   * bounds - {<ZOO.Bounds>}
3910   */
3911  setBounds: function(bounds) {
3912    if (bounds)
3913      this.bounds = bounds.clone();
3914  },
3915  /**
3916   * Method: clearBounds
3917   * Nullify this components bounds and that of its parent as well.
3918   */
3919  clearBounds: function() {
3920    this.bounds = null;
3921    if (this.parent)
3922      this.parent.clearBounds();
3923  },
3924  /**
3925   * Method: getBounds
3926   * Get the bounds for this Geometry. If bounds is not set, it
3927   * is calculated again, this makes queries faster.
3928   *
3929   * Returns:
3930   * {<ZOO.Bounds>}
3931   */
3932  getBounds: function() {
3933    if (this.bounds == null) {
3934      this.calculateBounds();
3935    }
3936    return this.bounds;
3937  },
3938  /**
3939   * Method: calculateBounds
3940   * Recalculate the bounds for the geometry.
3941   */
3942  calculateBounds: function() {
3943    // This should be overridden by subclasses.
3944    return this.bounds;
3945  },
3946  distanceTo: function(geometry, options) {
3947  },
3948  getVertices: function(nodes) {
3949  },
3950  getLength: function() {
3951    return 0.0;
3952  },
3953  getArea: function() {
3954    return 0.0;
3955  },
3956  getCentroid: function() {
3957    return null;
3958  },
3959  /**
3960   * Method: toString
3961   * Returns the Well-Known Text representation of a geometry
3962   *
3963   * Returns:
3964   * {String} Well-Known Text
3965   */
3966  toString: function() {
3967    return ZOO.Format.WKT.prototype.write(
3968        new ZOO.Feature(this)
3969    );
3970  },
3971  CLASS_NAME: 'ZOO.Geometry'
3972});
3973/**
3974 * Function: ZOO.Geometry.fromWKT
3975 * Generate a geometry given a Well-Known Text string.
3976 *
3977 * Parameters:
3978 * wkt - {String} A string representing the geometry in Well-Known Text.
3979 *
3980 * Returns:
3981 * {<ZOO.Geometry>} A geometry of the appropriate class.
3982 */
3983ZOO.Geometry.fromWKT = function(wkt) {
3984  var format = arguments.callee.format;
3985  if(!format) {
3986    format = new ZOO.Format.WKT();
3987    arguments.callee.format = format;
3988  }
3989  var geom;
3990  var result = format.read(wkt);
3991  if(result instanceof ZOO.Feature) {
3992    geom = result.geometry;
3993  } else if(result instanceof Array) {
3994    var len = result.length;
3995    var components = new Array(len);
3996    for(var i=0; i<len; ++i) {
3997      components[i] = result[i].geometry;
3998    }
3999    geom = new ZOO.Geometry.Collection(components);
4000  }
4001  return geom;
4002};
4003ZOO.Geometry.segmentsIntersect = function(seg1, seg2, options) {
4004  var point = options && options.point;
4005  var tolerance = options && options.tolerance;
4006  var intersection = false;
4007  var x11_21 = seg1.x1 - seg2.x1;
4008  var y11_21 = seg1.y1 - seg2.y1;
4009  var x12_11 = seg1.x2 - seg1.x1;
4010  var y12_11 = seg1.y2 - seg1.y1;
4011  var y22_21 = seg2.y2 - seg2.y1;
4012  var x22_21 = seg2.x2 - seg2.x1;
4013  var d = (y22_21 * x12_11) - (x22_21 * y12_11);
4014  var n1 = (x22_21 * y11_21) - (y22_21 * x11_21);
4015  var n2 = (x12_11 * y11_21) - (y12_11 * x11_21);
4016  if(d == 0) {
4017    // parallel
4018    if(n1 == 0 && n2 == 0) {
4019      // coincident
4020      intersection = true;
4021    }
4022  } else {
4023    var along1 = n1 / d;
4024    var along2 = n2 / d;
4025    if(along1 >= 0 && along1 <= 1 && along2 >=0 && along2 <= 1) {
4026      // intersect
4027      if(!point) {
4028        intersection = true;
4029      } else {
4030        // calculate the intersection point
4031        var x = seg1.x1 + (along1 * x12_11);
4032        var y = seg1.y1 + (along1 * y12_11);
4033        intersection = new ZOO.Geometry.Point(x, y);
4034      }
4035    }
4036  }
4037  if(tolerance) {
4038    var dist;
4039    if(intersection) {
4040      if(point) {
4041        var segs = [seg1, seg2];
4042        var seg, x, y;
4043        // check segment endpoints for proximity to intersection
4044        // set intersection to first endpoint within the tolerance
4045        outer: for(var i=0; i<2; ++i) {
4046          seg = segs[i];
4047          for(var j=1; j<3; ++j) {
4048            x = seg["x" + j];
4049            y = seg["y" + j];
4050            dist = Math.sqrt(
4051                Math.pow(x - intersection.x, 2) +
4052                Math.pow(y - intersection.y, 2)
4053            );
4054            if(dist < tolerance) {
4055              intersection.x = x;
4056              intersection.y = y;
4057              break outer;
4058            }
4059          }
4060        }
4061      }
4062    } else {
4063      // no calculated intersection, but segments could be within
4064      // the tolerance of one another
4065      var segs = [seg1, seg2];
4066      var source, target, x, y, p, result;
4067      // check segment endpoints for proximity to intersection
4068      // set intersection to first endpoint within the tolerance
4069      outer: for(var i=0; i<2; ++i) {
4070        source = segs[i];
4071        target = segs[(i+1)%2];
4072        for(var j=1; j<3; ++j) {
4073          p = {x: source["x"+j], y: source["y"+j]};
4074          result = ZOO.Geometry.distanceToSegment(p, target);
4075          if(result.distance < tolerance) {
4076            if(point) {
4077              intersection = new ZOO.Geometry.Point(p.x, p.y);
4078            } else {
4079              intersection = true;
4080            }
4081            break outer;
4082          }
4083        }
4084      }
4085    }
4086  }
4087  return intersection;
4088};
4089ZOO.Geometry.distanceToSegment = function(point, segment) {
4090  var x0 = point.x;
4091  var y0 = point.y;
4092  var x1 = segment.x1;
4093  var y1 = segment.y1;
4094  var x2 = segment.x2;
4095  var y2 = segment.y2;
4096  var dx = x2 - x1;
4097  var dy = y2 - y1;
4098  var along = ((dx * (x0 - x1)) + (dy * (y0 - y1))) /
4099               (Math.pow(dx, 2) + Math.pow(dy, 2));
4100  var x, y;
4101  if(along <= 0.0) {
4102    x = x1;
4103    y = y1;
4104  } else if(along >= 1.0) {
4105    x = x2;
4106    y = y2;
4107  } else {
4108    x = x1 + along * dx;
4109    y = y1 + along * dy;
4110  }
4111  return {
4112    distance: Math.sqrt(Math.pow(x - x0, 2) + Math.pow(y - y0, 2)),
4113    x: x, y: y
4114  };
4115};
4116/**
4117 * Class: ZOO.Geometry.Collection
4118 * A Collection is exactly what it sounds like: A collection of different
4119 * Geometries. These are stored in the local parameter <components> (which
4120 * can be passed as a parameter to the constructor).
4121 *
4122 * As new geometries are added to the collection, they are NOT cloned.
4123 * When removing geometries, they need to be specified by reference (ie you
4124 * have to pass in the *exact* geometry to be removed).
4125 *
4126 * The <getArea> and <getLength> functions here merely iterate through
4127 * the components, summing their respective areas and lengths.
4128 *
4129 * Create a new instance with the <ZOO.Geometry.Collection> constructor.
4130 *
4131 * Inerhits from:
4132 *  - <ZOO.Geometry>
4133 */
4134ZOO.Geometry.Collection = ZOO.Class(ZOO.Geometry, {
4135  /**
4136   * Property: components
4137   * {Array(<ZOO.Geometry>)} The component parts of this geometry
4138   */
4139  components: null,
4140  /**
4141   * Property: componentTypes
4142   * {Array(String)} An array of class names representing the types of
4143   * components that the collection can include.  A null value means the
4144   * component types are not restricted.
4145   */
4146  componentTypes: null,
4147  /**
4148   * Constructor: ZOO.Geometry.Collection
4149   * Creates a Geometry Collection -- a list of geoms.
4150   *
4151   * Parameters:
4152   * components - {Array(<ZOO.Geometry>)} Optional array of geometries
4153   *
4154   */
4155  initialize: function (components) {
4156    ZOO.Geometry.prototype.initialize.apply(this, arguments);
4157    this.components = [];
4158    if (components != null) {
4159      this.addComponents(components);
4160    }
4161  },
4162  /**
4163   * Method: destroy
4164   * Destroy this geometry.
4165   */
4166  destroy: function () {
4167    this.components.length = 0;
4168    this.components = null;
4169  },
4170  /**
4171   * Method: clone
4172   * Clone this geometry.
4173   *
4174   * Returns:
4175   * {<ZOO.Geometry.Collection>} An exact clone of this collection
4176   */
4177  clone: function() {
4178    var geometry = eval("new " + this.CLASS_NAME + "()");
4179    for(var i=0, len=this.components.length; i<len; i++) {
4180      geometry.addComponent(this.components[i].clone());
4181    }
4182    return geometry;
4183  },
4184  /**
4185   * Method: getComponentsString
4186   * Get a string representing the components for this collection
4187   *
4188   * Returns:
4189   * {String} A string representation of the components of this geometry
4190   */
4191  getComponentsString: function(){
4192    var strings = [];
4193    for(var i=0, len=this.components.length; i<len; i++) {
4194      strings.push(this.components[i].toShortString()); 
4195    }
4196    return strings.join(",");
4197  },
4198  /**
4199   * Method: calculateBounds
4200   * Recalculate the bounds by iterating through the components and
4201   * calling extendBounds() on each item.
4202   */
4203  calculateBounds: function() {
4204    this.bounds = null;
4205    if ( this.components && this.components.length > 0) {
4206      this.setBounds(this.components[0].getBounds());
4207      for (var i=1, len=this.components.length; i<len; i++) {
4208        this.extendBounds(this.components[i].getBounds());
4209      }
4210    }
4211    return this.bounds
4212  },
4213  /**
4214   * APIMethod: addComponents
4215   * Add components to this geometry.
4216   *
4217   * Parameters:
4218   * components - {Array(<ZOO.Geometry>)} An array of geometries to add
4219   */
4220  addComponents: function(components){
4221    if(!(components instanceof Array))
4222      components = [components];
4223    for(var i=0, len=components.length; i<len; i++) {
4224      this.addComponent(components[i]);
4225    }
4226  },
4227  /**
4228   * Method: addComponent
4229   * Add a new component (geometry) to the collection.  If this.componentTypes
4230   * is set, then the component class name must be in the componentTypes array.
4231   *
4232   * The bounds cache is reset.
4233   *
4234   * Parameters:
4235   * component - {<ZOO.Geometry>} A geometry to add
4236   * index - {int} Optional index into the array to insert the component
4237   *
4238   * Returns:
4239   * {Boolean} The component geometry was successfully added
4240   */
4241  addComponent: function(component, index) {
4242    var added = false;
4243    if(component) {
4244      if(this.componentTypes == null ||
4245          (ZOO.indexOf(this.componentTypes,
4246                       component.CLASS_NAME) > -1)) {
4247        if(index != null && (index < this.components.length)) {
4248          var components1 = this.components.slice(0, index);
4249          var components2 = this.components.slice(index, 
4250                                                  this.components.length);
4251          components1.push(component);
4252          this.components = components1.concat(components2);
4253        } else {
4254          this.components.push(component);
4255        }
4256        component.parent = this;
4257        this.clearBounds();
4258        added = true;
4259      }
4260    }
4261    return added;
4262  },
4263  /**
4264   * Method: removeComponents
4265   * Remove components from this geometry.
4266   *
4267   * Parameters:
4268   * components - {Array(<ZOO.Geometry>)} The components to be removed
4269   */
4270  removeComponents: function(components) {
4271    if(!(components instanceof Array))
4272      components = [components];
4273    for(var i=components.length-1; i>=0; --i) {
4274      this.removeComponent(components[i]);
4275    }
4276  },
4277  /**
4278   * Method: removeComponent
4279   * Remove a component from this geometry.
4280   *
4281   * Parameters:
4282   * component - {<ZOO.Geometry>}
4283   */
4284  removeComponent: function(component) {     
4285    ZOO.removeItem(this.components, component);
4286    // clearBounds() so that it gets recalculated on the next call
4287    // to this.getBounds();
4288    this.clearBounds();
4289  },
4290  /**
4291   * Method: getLength
4292   * Calculate the length of this geometry
4293   *
4294   * Returns:
4295   * {Float} The length of the geometry
4296   */
4297  getLength: function() {
4298    var length = 0.0;
4299    for (var i=0, len=this.components.length; i<len; i++) {
4300      length += this.components[i].getLength();
4301    }
4302    return length;
4303  },
4304  /**
4305   * APIMethod: getArea
4306   * Calculate the area of this geometry. Note how this function is
4307   * overridden in <ZOO.Geometry.Polygon>.
4308   *
4309   * Returns:
4310   * {Float} The area of the collection by summing its parts
4311   */
4312  getArea: function() {
4313    var area = 0.0;
4314    for (var i=0, len=this.components.length; i<len; i++) {
4315      area += this.components[i].getArea();
4316    }
4317    return area;
4318  },
4319  /**
4320   * APIMethod: getGeodesicArea
4321   * Calculate the approximate area of the polygon were it projected onto
4322   *     the earth.
4323   *
4324   * Parameters:
4325   * projection - {<ZOO.Projection>} The spatial reference system
4326   *     for the geometry coordinates.  If not provided, Geographic/WGS84 is
4327   *     assumed.
4328   *
4329   * Reference:
4330   * Robert. G. Chamberlain and William H. Duquette, "Some Algorithms for
4331   *     Polygons on a Sphere", JPL Publication 07-03, Jet Propulsion
4332   *     Laboratory, Pasadena, CA, June 2007 http://trs-new.jpl.nasa.gov/dspace/handle/2014/40409
4333   *
4334   * Returns:
4335   * {float} The approximate geodesic area of the geometry in square meters.
4336   */
4337  getGeodesicArea: function(projection) {
4338    var area = 0.0;
4339    for(var i=0, len=this.components.length; i<len; i++) {
4340      area += this.components[i].getGeodesicArea(projection);
4341    }
4342    return area;
4343  },
4344  /**
4345   * Method: getCentroid
4346   *
4347   * Returns:
4348   * {<ZOO.Geometry.Point>} The centroid of the collection
4349   */
4350  getCentroid: function() {
4351    return this.components.length && this.components[0].getCentroid();
4352  },
4353  /**
4354   * Method: getGeodesicLength
4355   * Calculate the approximate length of the geometry were it projected onto
4356   *     the earth.
4357   *
4358   * Parameters:
4359   * projection - {<ZOO.Projection>} The spatial reference system
4360   *     for the geometry coordinates.  If not provided, Geographic/WGS84 is
4361   *     assumed.
4362   *
4363   * Returns:
4364   * {Float} The appoximate geodesic length of the geometry in meters.
4365   */
4366  getGeodesicLength: function(projection) {
4367    var length = 0.0;
4368    for(var i=0, len=this.components.length; i<len; i++) {
4369      length += this.components[i].getGeodesicLength(projection);
4370    }
4371    return length;
4372  },
4373  /**
4374   * Method: move
4375   * Moves a geometry by the given displacement along positive x and y axes.
4376   *     This modifies the position of the geometry and clears the cached
4377   *     bounds.
4378   *
4379   * Parameters:
4380   * x - {Float} Distance to move geometry in positive x direction.
4381   * y - {Float} Distance to move geometry in positive y direction.
4382   */
4383  move: function(x, y) {
4384    for(var i=0, len=this.components.length; i<len; i++) {
4385      this.components[i].move(x, y);
4386    }
4387  },
4388  /**
4389   * Method: rotate
4390   * Rotate a geometry around some origin
4391   *
4392   * Parameters:
4393   * angle - {Float} Rotation angle in degrees (measured counterclockwise
4394   *                 from the positive x-axis)
4395   * origin - {<ZOO.Geometry.Point>} Center point for the rotation
4396   */
4397  rotate: function(angle, origin) {
4398    for(var i=0, len=this.components.length; i<len; ++i) {
4399      this.components[i].rotate(angle, origin);
4400    }
4401  },
4402  /**
4403   * Method: resize
4404   * Resize a geometry relative to some origin.  Use this method to apply
4405   *     a uniform scaling to a geometry.
4406   *
4407   * Parameters:
4408   * scale - {Float} Factor by which to scale the geometry.  A scale of 2
4409   *                 doubles the size of the geometry in each dimension
4410   *                 (lines, for example, will be twice as long, and polygons
4411   *                 will have four times the area).
4412   * origin - {<ZOO.Geometry.Point>} Point of origin for resizing
4413   * ratio - {Float} Optional x:y ratio for resizing.  Default ratio is 1.
4414   *
4415   * Returns:
4416   * {ZOO.Geometry} - The current geometry.
4417   */
4418  resize: function(scale, origin, ratio) {
4419    for(var i=0; i<this.components.length; ++i) {
4420      this.components[i].resize(scale, origin, ratio);
4421    }
4422    return this;
4423  },
4424  distanceTo: function(geometry, options) {
4425    var edge = !(options && options.edge === false);
4426    var details = edge && options && options.details;
4427    var result, best;
4428    var min = Number.POSITIVE_INFINITY;
4429    for(var i=0, len=this.components.length; i<len; ++i) {
4430      result = this.components[i].distanceTo(geometry, options);
4431      distance = details ? result.distance : result;
4432      if(distance < min) {
4433        min = distance;
4434        best = result;
4435        if(min == 0)
4436          break;
4437      }
4438    }
4439    return best;
4440  },
4441  /**
4442   * Method: equals
4443   * Determine whether another geometry is equivalent to this one.  Geometries
4444   *     are considered equivalent if all components have the same coordinates.
4445   *
4446   * Parameters:
4447   * geom - {<ZOO.Geometry>} The geometry to test.
4448   *
4449   * Returns:
4450   * {Boolean} The supplied geometry is equivalent to this geometry.
4451   */
4452  equals: function(geometry) {
4453    var equivalent = true;
4454    if(!geometry || !geometry.CLASS_NAME ||
4455       (this.CLASS_NAME != geometry.CLASS_NAME))
4456      equivalent = false;
4457    else if(!(geometry.components instanceof Array) ||
4458             (geometry.components.length != this.components.length))
4459      equivalent = false;
4460    else
4461      for(var i=0, len=this.components.length; i<len; ++i) {
4462        if(!this.components[i].equals(geometry.components[i])) {
4463          equivalent = false;
4464          break;
4465        }
4466      }
4467    return equivalent;
4468  },
4469  /**
4470   * Method: transform
4471   * Reproject the components geometry from source to dest.
4472   *
4473   * Parameters:
4474   * source - {<ZOO.Projection>}
4475   * dest - {<ZOO.Projection>}
4476   *
4477   * Returns:
4478   * {<ZOO.Geometry>}
4479   */
4480  transform: function(source, dest) {
4481    if (source && dest) {
4482      for (var i=0, len=this.components.length; i<len; i++) { 
4483        var component = this.components[i];
4484        component.transform(source, dest);
4485      }
4486      this.bounds = null;
4487    }
4488    return this;
4489  },
4490  /**
4491   * Method: intersects
4492   * Determine if the input geometry intersects this one.
4493   *
4494   * Parameters:
4495   * geometry - {<ZOO.Geometry>} Any type of geometry.
4496   *
4497   * Returns:
4498   * {Boolean} The input geometry intersects this one.
4499   */
4500  intersects: function(geometry) {
4501    var intersect = false;
4502    for(var i=0, len=this.components.length; i<len; ++ i) {
4503      intersect = geometry.intersects(this.components[i]);
4504      if(intersect)
4505        break;
4506    }
4507    return intersect;
4508  },
4509  /**
4510   * Method: getVertices
4511   * Return a list of all points in this geometry.
4512   *
4513   * Parameters:
4514   * nodes - {Boolean} For lines, only return vertices that are
4515   *     endpoints.  If false, for lines, only vertices that are not
4516   *     endpoints will be returned.  If not provided, all vertices will
4517   *     be returned.
4518   *
4519   * Returns:
4520   * {Array} A list of all vertices in the geometry.
4521   */
4522  getVertices: function(nodes) {
4523    var vertices = [];
4524    for(var i=0, len=this.components.length; i<len; ++i) {
4525      Array.prototype.push.apply(
4526          vertices, this.components[i].getVertices(nodes)
4527          );
4528    }
4529    return vertices;
4530  },
4531  CLASS_NAME: 'ZOO.Geometry.Collection'
4532});
4533/**
4534 * Class: ZOO.Geometry.Point
4535 * Point geometry class.
4536 *
4537 * Inherits from:
4538 *  - <ZOO.Geometry>
4539 */
4540ZOO.Geometry.Point = ZOO.Class(ZOO.Geometry, {
4541  /**
4542   * Property: x
4543   * {float}
4544   */
4545  x: null,
4546  /**
4547   * Property: y
4548   * {float}
4549   */
4550  y: null,
4551  /**
4552   * Constructor: ZOO.Geometry.Point
4553   * Construct a point geometry.
4554   *
4555   * Parameters:
4556   * x - {float}
4557   * y - {float}
4558   *
4559   */
4560  initialize: function(x, y) {
4561    ZOO.Geometry.prototype.initialize.apply(this, arguments);
4562    this.x = parseFloat(x);
4563    this.y = parseFloat(y);
4564  },
4565  /**
4566   * Method: clone
4567   *
4568   * Returns:
4569   * {<ZOO.Geometry.Point>} An exact clone of this ZOO.Geometry.Point
4570   */
4571  clone: function(obj) {
4572    if (obj == null)
4573      obj = new ZOO.Geometry.Point(this.x, this.y);
4574    // catch any randomly tagged-on properties
4575    // ZOO.Util.applyDefaults(obj, this);
4576    return obj;
4577  },
4578  /**
4579   * Method: calculateBounds
4580   * Create a new Bounds based on the x/y
4581   */
4582  calculateBounds: function () {
4583    this.bounds = new ZOO.Bounds(this.x, this.y,
4584                                        this.x, this.y);
4585  },
4586  distanceTo: function(geometry, options) {
4587    var edge = !(options && options.edge === false);
4588    var details = edge && options && options.details;
4589    var distance, x0, y0, x1, y1, result;
4590    if(geometry instanceof ZOO.Geometry.Point) {
4591      x0 = this.x;
4592      y0 = this.y;
4593      x1 = geometry.x;
4594      y1 = geometry.y;
4595      distance = Math.sqrt(Math.pow(x0 - x1, 2) + Math.pow(y0 - y1, 2));
4596      result = !details ?
4597        distance : {x0: x0, y0: y0, x1: x1, y1: y1, distance: distance};
4598    } else {
4599      result = geometry.distanceTo(this, options);
4600      if(details) {
4601        // switch coord order since this geom is target
4602        result = {
4603          x0: result.x1, y0: result.y1,
4604          x1: result.x0, y1: result.y0,
4605          distance: result.distance
4606        };
4607      }
4608    }
4609    return result;
4610  },
4611  /**
4612   * Method: equals
4613   * Determine whether another geometry is equivalent to this one.  Geometries
4614   *     are considered equivalent if all components have the same coordinates.
4615   *
4616   * Parameters:
4617   * geom - {<ZOO.Geometry.Point>} The geometry to test.
4618   *
4619   * Returns:
4620   * {Boolean} The supplied geometry is equivalent to this geometry.
4621   */
4622  equals: function(geom) {
4623    var equals = false;
4624    if (geom != null)
4625      equals = ((this.x == geom.x && this.y == geom.y) ||
4626                (isNaN(this.x) && isNaN(this.y) && isNaN(geom.x) && isNaN(geom.y)));
4627    return equals;
4628  },
4629  /**
4630   * Method: toShortString
4631   *
4632   * Returns:
4633   * {String} Shortened String representation of Point object.
4634   *         (ex. <i>"5, 42"</i>)
4635   */
4636  toShortString: function() {
4637    return (this.x + ", " + this.y);
4638  },
4639  /**
4640   * Method: move
4641   * Moves a geometry by the given displacement along positive x and y axes.
4642   *     This modifies the position of the geometry and clears the cached
4643   *     bounds.
4644   *
4645   * Parameters:
4646   * x - {Float} Distance to move geometry in positive x direction.
4647   * y - {Float} Distance to move geometry in positive y direction.
4648   */
4649  move: function(x, y) {
4650    this.x = this.x + x;
4651    this.y = this.y + y;
4652    this.clearBounds();
4653  },
4654  /**
4655   * Method: rotate
4656   * Rotate a point around another.
4657   *
4658   * Parameters:
4659   * angle - {Float} Rotation angle in degrees (measured counterclockwise
4660   *                 from the positive x-axis)
4661   * origin - {<ZOO.Geometry.Point>} Center point for the rotation
4662   */
4663  rotate: function(angle, origin) {
4664        angle *= Math.PI / 180;
4665        var radius = this.distanceTo(origin);
4666        var theta = angle + Math.atan2(this.y - origin.y, this.x - origin.x);
4667        this.x = origin.x + (radius * Math.cos(theta));
4668        this.y = origin.y + (radius * Math.sin(theta));
4669        this.clearBounds();
4670  },
4671  /**
4672   * Method: getCentroid
4673   *
4674   * Returns:
4675   * {<ZOO.Geometry.Point>} The centroid of the collection
4676   */
4677  getCentroid: function() {
4678    return new ZOO.Geometry.Point(this.x, this.y);
4679  },
4680  /**
4681   * Method: resize
4682   * Resize a point relative to some origin.  For points, this has the effect
4683   *     of scaling a vector (from the origin to the point).  This method is
4684   *     more useful on geometry collection subclasses.
4685   *
4686   * Parameters:
4687   * scale - {Float} Ratio of the new distance from the origin to the old
4688   *                 distance from the origin.  A scale of 2 doubles the
4689   *                 distance between the point and origin.
4690   * origin - {<ZOO.Geometry.Point>} Point of origin for resizing
4691   * ratio - {Float} Optional x:y ratio for resizing.  Default ratio is 1.
4692   *
4693   * Returns:
4694   * {ZOO.Geometry} - The current geometry.
4695   */
4696  resize: function(scale, origin, ratio) {
4697    ratio = (ratio == undefined) ? 1 : ratio;
4698    this.x = origin.x + (scale * ratio * (this.x - origin.x));
4699    this.y = origin.y + (scale * (this.y - origin.y));
4700    this.clearBounds();
4701    return this;
4702  },
4703  /**
4704   * Method: intersects
4705   * Determine if the input geometry intersects this one.
4706   *
4707   * Parameters:
4708   * geometry - {<ZOO.Geometry>} Any type of geometry.
4709   *
4710   * Returns:
4711   * {Boolean} The input geometry intersects this one.
4712   */
4713  intersects: function(geometry) {
4714    var intersect = false;
4715    if(geometry.CLASS_NAME == "ZOO.Geometry.Point") {
4716      intersect = this.equals(geometry);
4717    } else {
4718      intersect = geometry.intersects(this);
4719    }
4720    return intersect;
4721  },
4722  /**
4723   * Method: transform
4724   * Translate the x,y properties of the point from source to dest.
4725   *
4726   * Parameters:
4727   * source - {<ZOO.Projection>}
4728   * dest - {<ZOO.Projection>}
4729   *
4730   * Returns:
4731   * {<ZOO.Geometry>}
4732   */
4733  transform: function(source, dest) {
4734    if ((source && dest)) {
4735      ZOO.Projection.transform(
4736          this, source, dest); 
4737      this.bounds = null;
4738    }       
4739    return this;
4740  },
4741  /**
4742   * Method: getVertices
4743   * Return a list of all points in this geometry.
4744   *
4745   * Parameters:
4746   * nodes - {Boolean} For lines, only return vertices that are
4747   *     endpoints.  If false, for lines, only vertices that are not
4748   *     endpoints will be returned.  If not provided, all vertices will
4749   *     be returned.
4750   *
4751   * Returns:
4752   * {Array} A list of all vertices in the geometry.
4753   */
4754  getVertices: function(nodes) {
4755    return [this];
4756  },
4757  CLASS_NAME: 'ZOO.Geometry.Point'
4758});
4759/**
4760 * Class: ZOO.Geometry.Surface
4761 * Surface geometry class.
4762 *
4763 * Inherits from:
4764 *  - <ZOO.Geometry>
4765 */
4766ZOO.Geometry.Surface = ZOO.Class(ZOO.Geometry, {
4767  initialize: function() {
4768    ZOO.Geometry.prototype.initialize.apply(this, arguments);
4769  },
4770  CLASS_NAME: "ZOO.Geometry.Surface"
4771});
4772/**
4773 * Class: ZOO.Geometry.MultiPoint
4774 * MultiPoint is a collection of Points. Create a new instance with the
4775 * <ZOO.Geometry.MultiPoint> constructor.
4776 *
4777 * Inherits from:
4778 *  - <ZOO.Geometry.Collection>
4779 */
4780ZOO.Geometry.MultiPoint = ZOO.Class(
4781  ZOO.Geometry.Collection, {
4782  /**
4783   * Property: componentTypes
4784   * {Array(String)} An array of class names representing the types of
4785   * components that the collection can include.  A null value means the
4786   * component types are not restricted.
4787   */
4788  componentTypes: ["ZOO.Geometry.Point"],
4789  /**
4790   * Constructor: ZOO.Geometry.MultiPoint
4791   * Create a new MultiPoint Geometry
4792   *
4793   * Parameters:
4794   * components - {Array(<ZOO.Geometry.Point>)}
4795   *
4796   * Returns:
4797   * {<ZOO.Geometry.MultiPoint>}
4798   */
4799  initialize: function(components) {
4800    ZOO.Geometry.Collection.prototype.initialize.apply(this,arguments);
4801  },
4802  /**
4803   * Method: addPoint
4804   * Wrapper for <ZOO.Geometry.Collection.addComponent>
4805   *
4806   * Parameters:
4807   * point - {<ZOO.Geometry.Point>} Point to be added
4808   * index - {Integer} Optional index
4809   */
4810  addPoint: function(point, index) {
4811    this.addComponent(point, index);
4812  },
4813  /**
4814   * Method: removePoint
4815   * Wrapper for <ZOO.Geometry.Collection.removeComponent>
4816   *
4817   * Parameters:
4818   * point - {<ZOO.Geometry.Point>} Point to be removed
4819   */
4820  removePoint: function(point){
4821    this.removeComponent(point);
4822  },
4823  CLASS_NAME: "ZOO.Geometry.MultiPoint"
4824});
4825/**
4826 * Class: ZOO.Geometry.Curve
4827 * A Curve is a MultiPoint, whose points are assumed to be connected. To
4828 * this end, we provide a "getLength()" function, which iterates through
4829 * the points, summing the distances between them.
4830 *
4831 * Inherits:
4832 *  - <ZOO.Geometry.MultiPoint>
4833 */
4834ZOO.Geometry.Curve = ZOO.Class(ZOO.Geometry.MultiPoint, {
4835  /**
4836   * Property: componentTypes
4837   * {Array(String)} An array of class names representing the types of
4838   *                 components that the collection can include.  A null
4839   *                 value means the component types are not restricted.
4840   */
4841  componentTypes: ["ZOO.Geometry.Point"],
4842  /**
4843   * Constructor: ZOO.Geometry.Curve
4844   *
4845   * Parameters:
4846   * point - {Array(<ZOO.Geometry.Point>)}
4847   */
4848  initialize: function(points) {
4849    ZOO.Geometry.MultiPoint.prototype.initialize.apply(this,arguments);
4850  },
4851  /**
4852   * Method: getLength
4853   *
4854   * Returns:
4855   * {Float} The length of the curve
4856   */
4857  getLength: function() {
4858    var length = 0.0;
4859    if ( this.components && (this.components.length > 1)) {
4860      for(var i=1, len=this.components.length; i<len; i++) {
4861        length += this.components[i-1].distanceTo(this.components[i]);
4862      }
4863    }
4864    return length;
4865  },
4866  /**
4867     * APIMethod: getGeodesicLength
4868     * Calculate the approximate length of the geometry were it projected onto
4869     *     the earth.
4870     *
4871     * projection - {<ZOO.Projection>} The spatial reference system
4872     *     for the geometry coordinates.  If not provided, Geographic/WGS84 is
4873     *     assumed.
4874     *
4875     * Returns:
4876     * {Float} The appoximate geodesic length of the geometry in meters.
4877     */
4878    getGeodesicLength: function(projection) {
4879      var geom = this;  // so we can work with a clone if needed
4880      if(projection) {
4881        var gg = new ZOO.Projection("EPSG:4326");
4882        if(!gg.equals(projection)) {
4883          geom = this.clone().transform(projection, gg);
4884       }
4885     }
4886     var length = 0.0;
4887     if(geom.components && (geom.components.length > 1)) {
4888       var p1, p2;
4889       for(var i=1, len=geom.components.length; i<len; i++) {
4890         p1 = geom.components[i-1];
4891         p2 = geom.components[i];
4892        // this returns km and requires x/y properties
4893        length += ZOO.distVincenty(p1,p2);
4894      }
4895    }
4896    // convert to m
4897    return length * 1000;
4898  },
4899  CLASS_NAME: "ZOO.Geometry.Curve"
4900});
4901/**
4902 * Class: ZOO.Geometry.LineString
4903 * A LineString is a Curve which, once two points have been added to it, can
4904 * never be less than two points long.
4905 *
4906 * Inherits from:
4907 *  - <ZOO.Geometry.Curve>
4908 */
4909ZOO.Geometry.LineString = ZOO.Class(ZOO.Geometry.Curve, {
4910  /**
4911   * Constructor: ZOO.Geometry.LineString
4912   * Create a new LineString geometry
4913   *
4914   * Parameters:
4915   * points - {Array(<ZOO.Geometry.Point>)} An array of points used to
4916   *          generate the linestring
4917   *
4918   */
4919  initialize: function(points) {
4920    ZOO.Geometry.Curve.prototype.initialize.apply(this, arguments);       
4921  },
4922  /**
4923   * Method: removeComponent
4924   * Only allows removal of a point if there are three or more points in
4925   * the linestring. (otherwise the result would be just a single point)
4926   *
4927   * Parameters:
4928   * point - {<ZOO.Geometry.Point>} The point to be removed
4929   */
4930  removeComponent: function(point) {
4931    if ( this.components && (this.components.length > 2))
4932      ZOO.Geometry.Collection.prototype.removeComponent.apply(this,arguments);
4933  },
4934  /**
4935   * Method: intersects
4936   * Test for instersection between two geometries.  This is a cheapo
4937   *     implementation of the Bently-Ottmann algorigithm.  It doesn't
4938   *     really keep track of a sweep line data structure.  It is closer
4939   *     to the brute force method, except that segments are sorted and
4940   *     potential intersections are only calculated when bounding boxes
4941   *     intersect.
4942   *
4943   * Parameters:
4944   * geometry - {<ZOO.Geometry>}
4945   *
4946   * Returns:
4947   * {Boolean} The input geometry intersects this geometry.
4948   */
4949  intersects: function(geometry) {
4950    var intersect = false;
4951    var type = geometry.CLASS_NAME;
4952    if(type == "ZOO.Geometry.LineString" ||
4953       type == "ZOO.Geometry.LinearRing" ||
4954       type == "ZOO.Geometry.Point") {
4955      var segs1 = this.getSortedSegments();
4956      var segs2;
4957      if(type == "ZOO.Geometry.Point")
4958        segs2 = [{
4959          x1: geometry.x, y1: geometry.y,
4960          x2: geometry.x, y2: geometry.y
4961        }];
4962      else
4963        segs2 = geometry.getSortedSegments();
4964      var seg1, seg1x1, seg1x2, seg1y1, seg1y2,
4965          seg2, seg2y1, seg2y2;
4966      // sweep right
4967      outer: for(var i=0, len=segs1.length; i<len; ++i) {
4968         seg1 = segs1[i];
4969         seg1x1 = seg1.x1;
4970         seg1x2 = seg1.x2;
4971         seg1y1 = seg1.y1;
4972         seg1y2 = seg1.y2;
4973         inner: for(var j=0, jlen=segs2.length; j<jlen; ++j) {
4974           seg2 = segs2[j];
4975           if(seg2.x1 > seg1x2)
4976             break;
4977           if(seg2.x2 < seg1x1)
4978             continue;
4979           seg2y1 = seg2.y1;
4980           seg2y2 = seg2.y2;
4981           if(Math.min(seg2y1, seg2y2) > Math.max(seg1y1, seg1y2))
4982             continue;
4983           if(Math.max(seg2y1, seg2y2) < Math.min(seg1y1, seg1y2))
4984             continue;
4985           if(ZOO.Geometry.segmentsIntersect(seg1, seg2)) {
4986             intersect = true;
4987             break outer;
4988           }
4989         }
4990      }
4991    } else {
4992      intersect = geometry.intersects(this);
4993    }
4994    return intersect;
4995  },
4996  /**
4997   * Method: getSortedSegments
4998   *
4999   * Returns:
5000   * {Array} An array of segment objects.  Segment objects have properties
5001   *     x1, y1, x2, and y2.  The start point is represented by x1 and y1.
5002   *     The end point is represented by x2 and y2.  Start and end are
5003   *     ordered so that x1 < x2.
5004   */
5005  getSortedSegments: function() {
5006    var numSeg = this.components.length - 1;
5007    var segments = new Array(numSeg);
5008    for(var i=0; i<numSeg; ++i) {
5009      point1 = this.components[i];
5010      point2 = this.components[i + 1];
5011      if(point1.x < point2.x)
5012        segments[i] = {
5013          x1: point1.x,
5014          y1: point1.y,
5015          x2: point2.x,
5016          y2: point2.y
5017        };
5018      else
5019        segments[i] = {
5020          x1: point2.x,
5021          y1: point2.y,
5022          x2: point1.x,
5023          y2: point1.y
5024        };
5025    }
5026    // more efficient to define this somewhere static
5027    function byX1(seg1, seg2) {
5028      return seg1.x1 - seg2.x1;
5029    }
5030    return segments.sort(byX1);
5031  },
5032  /**
5033   * Method: splitWithSegment
5034   * Split this geometry with the given segment.
5035   *
5036   * Parameters:
5037   * seg - {Object} An object with x1, y1, x2, and y2 properties referencing
5038   *     segment endpoint coordinates.
5039   * options - {Object} Properties of this object will be used to determine
5040   *     how the split is conducted.
5041   *
5042   * Valid options:
5043   * edge - {Boolean} Allow splitting when only edges intersect.  Default is
5044   *     true.  If false, a vertex on the source segment must be within the
5045   *     tolerance distance of the intersection to be considered a split.
5046   * tolerance - {Number} If a non-null value is provided, intersections
5047   *     within the tolerance distance of one of the source segment's
5048   *     endpoints will be assumed to occur at the endpoint.
5049   *
5050   * Returns:
5051   * {Object} An object with *lines* and *points* properties.  If the given
5052   *     segment intersects this linestring, the lines array will reference
5053   *     geometries that result from the split.  The points array will contain
5054   *     all intersection points.  Intersection points are sorted along the
5055   *     segment (in order from x1,y1 to x2,y2).
5056   */
5057  splitWithSegment: function(seg, options) {
5058    var edge = !(options && options.edge === false);
5059    var tolerance = options && options.tolerance;
5060    var lines = [];
5061    var verts = this.getVertices();
5062    var points = [];
5063    var intersections = [];
5064    var split = false;
5065    var vert1, vert2, point;
5066    var node, vertex, target;
5067    var interOptions = {point: true, tolerance: tolerance};
5068    var result = null;
5069    for(var i=0, stop=verts.length-2; i<=stop; ++i) {
5070      vert1 = verts[i];
5071      points.push(vert1.clone());
5072      vert2 = verts[i+1];
5073      target = {x1: vert1.x, y1: vert1.y, x2: vert2.x, y2: vert2.y};
5074      point = ZOO.Geometry.segmentsIntersect(seg, target, interOptions);
5075      if(point instanceof ZOO.Geometry.Point) {
5076        if((point.x === seg.x1 && point.y === seg.y1) ||
5077           (point.x === seg.x2 && point.y === seg.y2) ||
5078            point.equals(vert1) || point.equals(vert2))
5079          vertex = true;
5080        else
5081          vertex = false;
5082        if(vertex || edge) {
5083          // push intersections different than the previous
5084          if(!point.equals(intersections[intersections.length-1]))
5085            intersections.push(point.clone());
5086          if(i === 0) {
5087            if(point.equals(vert1))
5088              continue;
5089          }
5090          if(point.equals(vert2))
5091            continue;
5092          split = true;
5093          if(!point.equals(vert1))
5094            points.push(point);
5095          lines.push(new ZOO.Geometry.LineString(points));
5096          points = [point.clone()];
5097        }
5098      }
5099    }
5100    if(split) {
5101      points.push(vert2.clone());
5102      lines.push(new ZOO.Geometry.LineString(points));
5103    }
5104    if(intersections.length > 0) {
5105      // sort intersections along segment
5106      var xDir = seg.x1 < seg.x2 ? 1 : -1;
5107      var yDir = seg.y1 < seg.y2 ? 1 : -1;
5108      result = {
5109        lines: lines,
5110        points: intersections.sort(function(p1, p2) {
5111           return (xDir * p1.x - xDir * p2.x) || (yDir * p1.y - yDir * p2.y);
5112        })
5113      };
5114    }
5115    return result;
5116  },
5117  /**
5118   * Method: split
5119   * Use this geometry (the source) to attempt to split a target geometry.
5120   *
5121   * Parameters:
5122   * target - {<ZOO.Geometry>} The target geometry.
5123   * options - {Object} Properties of this object will be used to determine
5124   *     how the split is conducted.
5125   *
5126   * Valid options:
5127   * mutual - {Boolean} Split the source geometry in addition to the target
5128   *     geometry.  Default is false.
5129   * edge - {Boolean} Allow splitting when only edges intersect.  Default is
5130   *     true.  If false, a vertex on the source must be within the tolerance
5131   *     distance of the intersection to be considered a split.
5132   * tolerance - {Number} If a non-null value is provided, intersections
5133   *     within the tolerance distance of an existing vertex on the source
5134   *     will be assumed to occur at the vertex.
5135   *
5136   * Returns:
5137   * {Array} A list of geometries (of this same type as the target) that
5138   *     result from splitting the target with the source geometry.  The
5139   *     source and target geometry will remain unmodified.  If no split
5140   *     results, null will be returned.  If mutual is true and a split
5141   *     results, return will be an array of two arrays - the first will be
5142   *     all geometries that result from splitting the source geometry and
5143   *     the second will be all geometries that result from splitting the
5144   *     target geometry.
5145   */
5146  split: function(target, options) {
5147    var results = null;
5148    var mutual = options && options.mutual;
5149    var sourceSplit, targetSplit, sourceParts, targetParts;
5150    if(target instanceof ZOO.Geometry.LineString) {
5151      var verts = this.getVertices();
5152      var vert1, vert2, seg, splits, lines, point;
5153      var points = [];
5154      sourceParts = [];
5155      for(var i=0, stop=verts.length-2; i<=stop; ++i) {
5156        vert1 = verts[i];
5157        vert2 = verts[i+1];
5158        seg = {
5159          x1: vert1.x, y1: vert1.y,
5160          x2: vert2.x, y2: vert2.y
5161        };
5162        targetParts = targetParts || [target];
5163        if(mutual)
5164          points.push(vert1.clone());
5165        for(var j=0; j<targetParts.length; ++j) {
5166          splits = targetParts[j].splitWithSegment(seg, options);
5167          if(splits) {
5168            // splice in new features
5169            lines = splits.lines;
5170            if(lines.length > 0) {
5171              lines.unshift(j, 1);
5172              Array.prototype.splice.apply(targetParts, lines);
5173              j += lines.length - 2;
5174            }
5175            if(mutual) {
5176              for(var k=0, len=splits.points.length; k<len; ++k) {
5177                point = splits.points[k];
5178                if(!point.equals(vert1)) {
5179                  points.push(point);
5180                  sourceParts.push(new ZOO.Geometry.LineString(points));
5181                  if(point.equals(vert2))
5182                    points = [];
5183                  else
5184                    points = [point.clone()];
5185                }
5186              }
5187            }
5188          }
5189        }
5190      }
5191      if(mutual && sourceParts.length > 0 && points.length > 0) {
5192        points.push(vert2.clone());
5193        sourceParts.push(new ZOO.Geometry.LineString(points));
5194      }
5195    } else {
5196      results = target.splitWith(this, options);
5197    }
5198    if(targetParts && targetParts.length > 1)
5199      targetSplit = true;
5200    else
5201      targetParts = [];
5202    if(sourceParts && sourceParts.length > 1)
5203      sourceSplit = true;
5204    else
5205      sourceParts = [];
5206    if(targetSplit || sourceSplit) {
5207      if(mutual)
5208        results = [sourceParts, targetParts];
5209      else
5210        results = targetParts;
5211    }
5212    return results;
5213  },
5214  /**
5215   * Method: splitWith
5216   * Split this geometry (the target) with the given geometry (the source).
5217   *
5218   * Parameters:
5219   * geometry - {<ZOO.Geometry>} A geometry used to split this
5220   *     geometry (the source).
5221   * options - {Object} Properties of this object will be used to determine
5222   *     how the split is conducted.
5223   *
5224   * Valid options:
5225   * mutual - {Boolean} Split the source geometry in addition to the target
5226   *     geometry.  Default is false.
5227   * edge - {Boolean} Allow splitting when only edges intersect.  Default is
5228   *     true.  If false, a vertex on the source must be within the tolerance
5229   *     distance of the intersection to be considered a split.
5230   * tolerance - {Number} If a non-null value is provided, intersections
5231   *     within the tolerance distance of an existing vertex on the source
5232   *     will be assumed to occur at the vertex.
5233   *
5234   * Returns:
5235   * {Array} A list of geometries (of this same type as the target) that
5236   *     result from splitting the target with the source geometry.  The
5237   *     source and target geometry will remain unmodified.  If no split
5238   *     results, null will be returned.  If mutual is true and a split
5239   *     results, return will be an array of two arrays - the first will be
5240   *     all geometries that result from splitting the source geometry and
5241   *     the second will be all geometries that result from splitting the
5242   *     target geometry.
5243   */
5244  splitWith: function(geometry, options) {
5245    return geometry.split(this, options);
5246  },
5247  /**
5248   * Method: getVertices
5249   * Return a list of all points in this geometry.
5250   *
5251   * Parameters:
5252   * nodes - {Boolean} For lines, only return vertices that are
5253   *     endpoints.  If false, for lines, only vertices that are not
5254   *     endpoints will be returned.  If not provided, all vertices will
5255   *     be returned.
5256   *
5257   * Returns:
5258   * {Array} A list of all vertices in the geometry.
5259   */
5260  getVertices: function(nodes) {
5261    var vertices;
5262    if(nodes === true)
5263      vertices = [
5264        this.components[0],
5265        this.components[this.components.length-1]
5266      ];
5267    else if (nodes === false)
5268      vertices = this.components.slice(1, this.components.length-1);
5269    else
5270      vertices = this.components.slice();
5271    return vertices;
5272  },
5273  distanceTo: function(geometry, options) {
5274    var edge = !(options && options.edge === false);
5275    var details = edge && options && options.details;
5276    var result, best = {};
5277    var min = Number.POSITIVE_INFINITY;
5278    if(geometry instanceof ZOO.Geometry.Point) {
5279      var segs = this.getSortedSegments();
5280      var x = geometry.x;
5281      var y = geometry.y;
5282      var seg;
5283      for(var i=0, len=segs.length; i<len; ++i) {
5284        seg = segs[i];
5285        result = ZOO.Geometry.distanceToSegment(geometry, seg);
5286        if(result.distance < min) {
5287          min = result.distance;
5288          best = result;
5289          if(min === 0)
5290            break;
5291        } else {
5292          // if distance increases and we cross y0 to the right of x0, no need to keep looking.
5293          if(seg.x2 > x && ((y > seg.y1 && y < seg.y2) || (y < seg.y1 && y > seg.y2)))
5294            break;
5295        }
5296      }
5297      if(details)
5298        best = {
5299          distance: best.distance,
5300          x0: best.x, y0: best.y,
5301          x1: x, y1: y
5302        };
5303      else
5304        best = best.distance;
5305    } else if(geometry instanceof ZOO.Geometry.LineString) { 
5306      var segs0 = this.getSortedSegments();
5307      var segs1 = geometry.getSortedSegments();
5308      var seg0, seg1, intersection, x0, y0;
5309      var len1 = segs1.length;
5310      var interOptions = {point: true};
5311      outer: for(var i=0, len=segs0.length; i<len; ++i) {
5312        seg0 = segs0[i];
5313        x0 = seg0.x1;
5314        y0 = seg0.y1;
5315        for(var j=0; j<len1; ++j) {
5316          seg1 = segs1[j];
5317          intersection = ZOO.Geometry.segmentsIntersect(seg0, seg1, interOptions);
5318          if(intersection) {
5319            min = 0;
5320            best = {
5321              distance: 0,
5322              x0: intersection.x, y0: intersection.y,
5323              x1: intersection.x, y1: intersection.y
5324            };
5325            break outer;
5326          } else {
5327            result = ZOO.Geometry.distanceToSegment({x: x0, y: y0}, seg1);
5328            if(result.distance < min) {
5329              min = result.distance;
5330              best = {
5331                distance: min,
5332                x0: x0, y0: y0,
5333                x1: result.x, y1: result.y
5334              };
5335            }
5336          }
5337        }
5338      }
5339      if(!details)
5340        best = best.distance;
5341      if(min !== 0) {
5342        // check the final vertex in this line's sorted segments
5343        if(seg0) {
5344          result = geometry.distanceTo(
5345              new ZOO.Geometry.Point(seg0.x2, seg0.y2),
5346              options
5347              );
5348          var dist = details ? result.distance : result;
5349          if(dist < min) {
5350            if(details)
5351              best = {
5352                distance: min,
5353                x0: result.x1, y0: result.y1,
5354                x1: result.x0, y1: result.y0
5355              };
5356            else
5357              best = dist;
5358          }
5359        }
5360      }
5361    } else {
5362      best = geometry.distanceTo(this, options);
5363      // swap since target comes from this line
5364      if(details)
5365        best = {
5366          distance: best.distance,
5367          x0: best.x1, y0: best.y1,
5368          x1: best.x0, y1: best.y0
5369        };
5370    }
5371    return best;
5372  },
5373  CLASS_NAME: "ZOO.Geometry.LineString"
5374});
5375/**
5376 * Class: ZOO.Geometry.LinearRing
5377 *
5378 * A Linear Ring is a special LineString which is closed. It closes itself
5379 * automatically on every addPoint/removePoint by adding a copy of the first
5380 * point as the last point.
5381 *
5382 * Also, as it is the first in the line family to close itself, a getArea()
5383 * function is defined to calculate the enclosed area of the linearRing
5384 *
5385 * Inherits:
5386 *  - <ZOO.Geometry.LineString>
5387 */
5388ZOO.Geometry.LinearRing = ZOO.Class(
5389  ZOO.Geometry.LineString, {
5390  /**
5391   * Property: componentTypes
5392   * {Array(String)} An array of class names representing the types of
5393   *                 components that the collection can include.  A null
5394   *                 value means the component types are not restricted.
5395   */
5396  componentTypes: ["ZOO.Geometry.Point"],
5397  /**
5398   * Constructor: ZOO.Geometry.LinearRing
5399   * Linear rings are constructed with an array of points.  This array
5400   *     can represent a closed or open ring.  If the ring is open (the last
5401   *     point does not equal the first point), the constructor will close
5402   *     the ring.  If the ring is already closed (the last point does equal
5403   *     the first point), it will be left closed.
5404   *
5405   * Parameters:
5406   * points - {Array(<ZOO.Geometry.Point>)} points
5407   */
5408  initialize: function(points) {
5409    ZOO.Geometry.LineString.prototype.initialize.apply(this,arguments);
5410  },
5411  /**
5412   * Method: addComponent
5413   * Adds a point to geometry components.  If the point is to be added to
5414   *     the end of the components array and it is the same as the last point
5415   *     already in that array, the duplicate point is not added.  This has
5416   *     the effect of closing the ring if it is not already closed, and
5417   *     doing the right thing if it is already closed.  This behavior can
5418   *     be overridden by calling the method with a non-null index as the
5419   *     second argument.
5420   *
5421   * Parameter:
5422   * point - {<ZOO.Geometry.Point>}
5423   * index - {Integer} Index into the array to insert the component
5424   *
5425   * Returns:
5426   * {Boolean} Was the Point successfully added?
5427   */
5428  addComponent: function(point, index) {
5429    var added = false;
5430    //remove last point
5431    var lastPoint = this.components.pop();
5432    // given an index, add the point
5433    // without an index only add non-duplicate points
5434    if(index != null || !point.equals(lastPoint))
5435      added = ZOO.Geometry.Collection.prototype.addComponent.apply(this,arguments);
5436    //append copy of first point
5437    var firstPoint = this.components[0];
5438    ZOO.Geometry.Collection.prototype.addComponent.apply(this,[firstPoint]);
5439    return added;
5440  },
5441  /**
5442   * APIMethod: removeComponent
5443   * Removes a point from geometry components.
5444   *
5445   * Parameters:
5446   * point - {<ZOO.Geometry.Point>}
5447   */
5448  removeComponent: function(point) {
5449    if (this.components.length > 4) {
5450      //remove last point
5451      this.components.pop();
5452      //remove our point
5453      ZOO.Geometry.Collection.prototype.removeComponent.apply(this,arguments);
5454      //append copy of first point
5455      var firstPoint = this.components[0];
5456      ZOO.Geometry.Collection.prototype.addComponent.apply(this,[firstPoint]);
5457    }
5458  },
5459  /**
5460   * Method: move
5461   * Moves a geometry by the given displacement along positive x and y axes.
5462   *     This modifies the position of the geometry and clears the cached
5463   *     bounds.
5464   *
5465   * Parameters:
5466   * x - {Float} Distance to move geometry in positive x direction.
5467   * y - {Float} Distance to move geometry in positive y direction.
5468   */
5469  move: function(x, y) {
5470    for(var i = 0, len=this.components.length; i<len - 1; i++) {
5471      this.components[i].move(x, y);
5472    }
5473  },
5474  /**
5475   * Method: rotate
5476   * Rotate a geometry around some origin
5477   *
5478   * Parameters:
5479   * angle - {Float} Rotation angle in degrees (measured counterclockwise
5480   *                 from the positive x-axis)
5481   * origin - {<ZOO.Geometry.Point>} Center point for the rotation
5482   */
5483  rotate: function(angle, origin) {
5484    for(var i=0, len=this.components.length; i<len - 1; ++i) {
5485      this.components[i].rotate(angle, origin);
5486    }
5487  },
5488  /**
5489   * Method: resize
5490   * Resize a geometry relative to some origin.  Use this method to apply
5491   *     a uniform scaling to a geometry.
5492   *
5493   * Parameters:
5494   * scale - {Float} Factor by which to scale the geometry.  A scale of 2
5495   *                 doubles the size of the geometry in each dimension
5496   *                 (lines, for example, will be twice as long, and polygons
5497   *                 will have four times the area).
5498   * origin - {<ZOO.Geometry.Point>} Point of origin for resizing
5499   * ratio - {Float} Optional x:y ratio for resizing.  Default ratio is 1.
5500   *
5501   * Returns:
5502   * {ZOO.Geometry} - The current geometry.
5503   */
5504  resize: function(scale, origin, ratio) {
5505    for(var i=0, len=this.components.length; i<len - 1; ++i) {
5506      this.components[i].resize(scale, origin, ratio);
5507    }
5508    return this;
5509  },
5510  /**
5511   * Method: transform
5512   * Reproject the components geometry from source to dest.
5513   *
5514   * Parameters:
5515   * source - {<ZOO.Projection>}
5516   * dest - {<ZOO.Projection>}
5517   *
5518   * Returns:
5519   * {<ZOO.Geometry>}
5520   */
5521  transform: function(source, dest) {
5522    if (source && dest) {
5523      for (var i=0, len=this.components.length; i<len - 1; i++) {
5524        var component = this.components[i];
5525        component.transform(source, dest);
5526      }
5527      this.bounds = null;
5528    }
5529    return this;
5530  },
5531  /**
5532   * Method: getCentroid
5533   *
5534   * Returns:
5535   * {<ZOO.Geometry.Point>} The centroid of the ring
5536   */
5537  getCentroid: function() {
5538    if ( this.components && (this.components.length > 2)) {
5539      var sumX = 0.0;
5540      var sumY = 0.0;
5541      for (var i = 0; i < this.components.length - 1; i++) {
5542        var b = this.components[i];
5543        var c = this.components[i+1];
5544        sumX += (b.x + c.x) * (b.x * c.y - c.x * b.y);
5545        sumY += (b.y + c.y) * (b.x * c.y - c.x * b.y);
5546      }
5547      var area = -1 * this.getArea();
5548      var x = sumX / (6 * area);
5549      var y = sumY / (6 * area);
5550    }
5551    return new ZOO.Geometry.Point(x, y);
5552  },
5553  /**
5554   * Method: getArea
5555   * Note - The area is positive if the ring is oriented CW, otherwise
5556   *         it will be negative.
5557   *
5558   * Returns:
5559   * {Float} The signed area for a ring.
5560   */
5561  getArea: function() {
5562    var area = 0.0;
5563    if ( this.components && (this.components.length > 2)) {
5564      var sum = 0.0;
5565      for (var i=0, len=this.components.length; i<len - 1; i++) {
5566        var b = this.components[i];
5567        var c = this.components[i+1];
5568        sum += (b.x + c.x) * (c.y - b.y);
5569      }
5570      area = - sum / 2.0;
5571    }
5572    return area;
5573  },
5574  /**
5575   * Method: getGeodesicArea
5576   * Calculate the approximate area of the polygon were it projected onto
5577   *     the earth.  Note that this area will be positive if ring is oriented
5578   *     clockwise, otherwise it will be negative.
5579   *
5580   * Parameters:
5581   * projection - {<ZOO.Projection>} The spatial reference system
5582   *     for the geometry coordinates.  If not provided, Geographic/WGS84 is
5583   *     assumed.
5584   *
5585   * Reference:
5586   * Robert. G. Chamberlain and William H. Duquette, "Some Algorithms for
5587   *     Polygons on a Sphere", JPL Publication 07-03, Jet Propulsion
5588   *     Laboratory, Pasadena, CA, June 2007 http://trs-new.jpl.nasa.gov/dspace/handle/2014/40409
5589   *
5590   * Returns:
5591   * {float} The approximate signed geodesic area of the polygon in square
5592   *     meters.
5593   */
5594  getGeodesicArea: function(projection) {
5595    var ring = this;  // so we can work with a clone if needed
5596    if(projection) {
5597      var gg = new ZOO.Projection("EPSG:4326");
5598      if(!gg.equals(projection)) {
5599        ring = this.clone().transform(projection, gg);
5600      }
5601    }
5602    var area = 0.0;
5603    var len = ring.components && ring.components.length;
5604    if(len > 2) {
5605      var p1, p2;
5606      for(var i=0; i<len-1; i++) {
5607        p1 = ring.components[i];
5608        p2 = ring.components[i+1];
5609        area += ZOO.rad(p2.x - p1.x) *
5610                (2 + Math.sin(ZOO.rad(p1.y)) +
5611                Math.sin(ZOO.rad(p2.y)));
5612      }
5613      area = area * 6378137.0 * 6378137.0 / 2.0;
5614    }
5615    return area;
5616  },
5617  /**
5618   * Method: containsPoint
5619   * Test if a point is inside a linear ring.  For the case where a point
5620   *     is coincident with a linear ring edge, returns 1.  Otherwise,
5621   *     returns boolean.
5622   *
5623   * Parameters:
5624   * point - {<ZOO.Geometry.Point>}
5625   *
5626   * Returns:
5627   * {Boolean | Number} The point is inside the linear ring.  Returns 1 if
5628   *     the point is coincident with an edge.  Returns boolean otherwise.
5629   */
5630  containsPoint: function(point) {
5631    var approx = OpenLayers.Number.limitSigDigs;
5632    var digs = 14;
5633    var px = approx(point.x, digs);
5634    var py = approx(point.y, digs);
5635    function getX(y, x1, y1, x2, y2) {
5636      return (((x1 - x2) * y) + ((x2 * y1) - (x1 * y2))) / (y1 - y2);
5637    }
5638    var numSeg = this.components.length - 1;
5639    var start, end, x1, y1, x2, y2, cx, cy;
5640    var crosses = 0;
5641    for(var i=0; i<numSeg; ++i) {
5642      start = this.components[i];
5643      x1 = approx(start.x, digs);
5644      y1 = approx(start.y, digs);
5645      end = this.components[i + 1];
5646      x2 = approx(end.x, digs);
5647      y2 = approx(end.y, digs);
5648
5649      /**
5650       * The following conditions enforce five edge-crossing rules:
5651       *    1. points coincident with edges are considered contained;
5652       *    2. an upward edge includes its starting endpoint, and
5653       *    excludes its final endpoint;
5654       *    3. a downward edge excludes its starting endpoint, and
5655       *    includes its final endpoint;
5656       *    4. horizontal edges are excluded; and
5657       *    5. the edge-ray intersection point must be strictly right
5658       *    of the point P.
5659       */
5660      if(y1 == y2) {
5661        // horizontal edge
5662        if(py == y1) {
5663          // point on horizontal line
5664          if(x1 <= x2 && (px >= x1 && px <= x2) || // right or vert
5665              x1 >= x2 && (px <= x1 && px >= x2)) { // left or vert
5666            // point on edge
5667            crosses = -1;
5668            break;
5669          }
5670        }
5671        // ignore other horizontal edges
5672        continue;
5673      }
5674      cx = approx(getX(py, x1, y1, x2, y2), digs);
5675      if(cx == px) {
5676        // point on line
5677        if(y1 < y2 && (py >= y1 && py <= y2) || // upward
5678            y1 > y2 && (py <= y1 && py >= y2)) { // downward
5679          // point on edge
5680          crosses = -1;
5681          break;
5682        }
5683      }
5684      if(cx <= px) {
5685        // no crossing to the right
5686        continue;
5687      }
5688      if(x1 != x2 && (cx < Math.min(x1, x2) || cx > Math.max(x1, x2))) {
5689        // no crossing
5690        continue;
5691      }
5692      if(y1 < y2 && (py >= y1 && py < y2) || // upward
5693          y1 > y2 && (py < y1 && py >= y2)) { // downward
5694        ++crosses;
5695      }
5696    }
5697    var contained = (crosses == -1) ?
5698      // on edge
5699      1 :
5700      // even (out) or odd (in)
5701      !!(crosses & 1);
5702
5703    return contained;
5704  },
5705  intersects: function(geometry) {
5706    var intersect = false;
5707    if(geometry.CLASS_NAME == "ZOO.Geometry.Point")
5708      intersect = this.containsPoint(geometry);
5709    else if(geometry.CLASS_NAME == "ZOO.Geometry.LineString")
5710      intersect = geometry.intersects(this);
5711    else if(geometry.CLASS_NAME == "ZOO.Geometry.LinearRing")
5712      intersect = ZOO.Geometry.LineString.prototype.intersects.apply(
5713          this, [geometry]
5714          );
5715    else
5716      for(var i=0, len=geometry.components.length; i<len; ++ i) {
5717        intersect = geometry.components[i].intersects(this);
5718        if(intersect)
5719          break;
5720      }
5721    return intersect;
5722  },
5723  getVertices: function(nodes) {
5724    return (nodes === true) ? [] : this.components.slice(0, this.components.length-1);
5725  },
5726  CLASS_NAME: "ZOO.Geometry.LinearRing"
5727});
5728/**
5729 * Class: ZOO.Geometry.MultiLineString
5730 * A MultiLineString is a geometry with multiple <ZOO.Geometry.LineString>
5731 * components.
5732 *
5733 * Inherits from:
5734 *  - <ZOO.Geometry.Collection>
5735 */
5736ZOO.Geometry.MultiLineString = ZOO.Class(
5737  ZOO.Geometry.Collection, {
5738  componentTypes: ["ZOO.Geometry.LineString"],
5739  /**
5740   * Constructor: ZOO.Geometry.MultiLineString
5741   * Constructor for a MultiLineString Geometry.
5742   *
5743   * Parameters:
5744   * components - {Array(<ZOO.Geometry.LineString>)}
5745   *
5746   */
5747  initialize: function(components) {
5748    ZOO.Geometry.Collection.prototype.initialize.apply(this,arguments);       
5749  },
5750  split: function(geometry, options) {
5751    var results = null;
5752    var mutual = options && options.mutual;
5753    var splits, sourceLine, sourceLines, sourceSplit, targetSplit;
5754    var sourceParts = [];
5755    var targetParts = [geometry];
5756    for(var i=0, len=this.components.length; i<len; ++i) {
5757      sourceLine = this.components[i];
5758      sourceSplit = false;
5759      for(var j=0; j < targetParts.length; ++j) { 
5760        splits = sourceLine.split(targetParts[j], options);
5761        if(splits) {
5762          if(mutual) {
5763            sourceLines = splits[0];
5764            for(var k=0, klen=sourceLines.length; k<klen; ++k) {
5765              if(k===0 && sourceParts.length)
5766                sourceParts[sourceParts.length-1].addComponent(
5767                  sourceLines[k]
5768                );
5769              else
5770                sourceParts.push(
5771                  new ZOO.Geometry.MultiLineString([
5772                    sourceLines[k]
5773                    ])
5774                );
5775            }
5776            sourceSplit = true;
5777            splits = splits[1];
5778          }
5779          if(splits.length) {
5780            // splice in new target parts
5781            splits.unshift(j, 1);
5782            Array.prototype.splice.apply(targetParts, splits);
5783            break;
5784          }
5785        }
5786      }
5787      if(!sourceSplit) {
5788        // source line was not hit
5789        if(sourceParts.length) {
5790          // add line to existing multi
5791          sourceParts[sourceParts.length-1].addComponent(
5792              sourceLine.clone()
5793              );
5794        } else {
5795          // create a fresh multi
5796          sourceParts = [
5797            new ZOO.Geometry.MultiLineString(
5798                sourceLine.clone()
5799                )
5800            ];
5801        }
5802      }
5803    }
5804    if(sourceParts && sourceParts.length > 1)
5805      sourceSplit = true;
5806    else
5807      sourceParts = [];
5808    if(targetParts && targetParts.length > 1)
5809      targetSplit = true;
5810    else
5811      targetParts = [];
5812    if(sourceSplit || targetSplit) {
5813      if(mutual)
5814        results = [sourceParts, targetParts];
5815      else
5816        results = targetParts;
5817    }
5818    return results;
5819  },
5820  splitWith: function(geometry, options) {
5821    var results = null;
5822    var mutual = options && options.mutual;
5823    var splits, targetLine, sourceLines, sourceSplit, targetSplit, sourceParts, targetParts;
5824    if(geometry instanceof ZOO.Geometry.LineString) {
5825      targetParts = [];
5826      sourceParts = [geometry];
5827      for(var i=0, len=this.components.length; i<len; ++i) {
5828        targetSplit = false;
5829        targetLine = this.components[i];
5830        for(var j=0; j<sourceParts.length; ++j) {
5831          splits = sourceParts[j].split(targetLine, options);
5832          if(splits) {
5833            if(mutual) {
5834              sourceLines = splits[0];
5835              if(sourceLines.length) {
5836                // splice in new source parts
5837                sourceLines.unshift(j, 1);
5838                Array.prototype.splice.apply(sourceParts, sourceLines);
5839                j += sourceLines.length - 2;
5840              }
5841              splits = splits[1];
5842              if(splits.length === 0) {
5843                splits = [targetLine.clone()];
5844              }
5845            }
5846            for(var k=0, klen=splits.length; k<klen; ++k) {
5847              if(k===0 && targetParts.length) {
5848                targetParts[targetParts.length-1].addComponent(
5849                    splits[k]
5850                    );
5851              } else {
5852                targetParts.push(
5853                    new ZOO.Geometry.MultiLineString([
5854                      splits[k]
5855                      ])
5856                    );
5857              }
5858            }
5859            targetSplit = true;                   
5860          }
5861        }
5862        if(!targetSplit) {
5863          // target component was not hit
5864          if(targetParts.length) {
5865            // add it to any existing multi-line
5866            targetParts[targetParts.length-1].addComponent(
5867                targetLine.clone()
5868                );
5869          } else {
5870            // or start with a fresh multi-line
5871            targetParts = [
5872              new ZOO.Geometry.MultiLineString([
5873                  targetLine.clone()
5874                  ])
5875              ];
5876          }
5877
5878        }
5879      }
5880    } else {
5881      results = geometry.split(this);
5882    }
5883    if(sourceParts && sourceParts.length > 1)
5884      sourceSplit = true;
5885    else
5886      sourceParts = [];
5887    if(targetParts && targetParts.length > 1)
5888      targetSplit = true;
5889    else
5890      targetParts = [];
5891    if(sourceSplit || targetSplit) {
5892      if(mutual)
5893        results = [sourceParts, targetParts];
5894      else
5895        results = targetParts;
5896    }
5897    return results;
5898  },
5899  CLASS_NAME: "ZOO.Geometry.MultiLineString"
5900});
5901/**
5902 * Class: ZOO.Geometry.Polygon
5903 * Polygon is a collection of <ZOO.Geometry.LinearRing>.
5904 *
5905 * Inherits from:
5906 *  - <ZOO.Geometry.Collection>
5907 */
5908ZOO.Geometry.Polygon = ZOO.Class(
5909  ZOO.Geometry.Collection, {
5910  componentTypes: ["ZOO.Geometry.LinearRing"],
5911  /**
5912   * Constructor: ZOO.Geometry.Polygon
5913   * Constructor for a Polygon geometry.
5914   * The first ring (this.component[0])is the outer bounds of the polygon and
5915   * all subsequent rings (this.component[1-n]) are internal holes.
5916   *
5917   *
5918   * Parameters:
5919   * components - {Array(<ZOO.Geometry.LinearRing>)}
5920   */
5921  initialize: function(components) {
5922    ZOO.Geometry.Collection.prototype.initialize.apply(this,arguments);
5923  },
5924  /**
5925   * Method: getArea
5926   * Calculated by subtracting the areas of the internal holes from the
5927   *   area of the outer hole.
5928   *
5929   * Returns:
5930   * {float} The area of the geometry
5931   */
5932  getArea: function() {
5933    var area = 0.0;
5934    if ( this.components && (this.components.length > 0)) {
5935      area += Math.abs(this.components[0].getArea());
5936      for (var i=1, len=this.components.length; i<len; i++) {
5937        area -= Math.abs(this.components[i].getArea());
5938      }
5939    }
5940    return area;
5941  },
5942  /**
5943   * APIMethod: getGeodesicArea
5944   * Calculate the approximate area of the polygon were it projected onto
5945   *     the earth.
5946   *
5947   * Parameters:
5948   * projection - {<ZOO.Projection>} The spatial reference system
5949   *     for the geometry coordinates.  If not provided, Geographic/WGS84 is
5950   *     assumed.
5951   *
5952   * Reference:
5953   * Robert. G. Chamberlain and William H. Duquette, "Some Algorithms for
5954   *     Polygons on a Sphere", JPL Publication 07-03, Jet Propulsion
5955   *     Laboratory, Pasadena, CA, June 2007 http://trs-new.jpl.nasa.gov/dspace/handle/2014/40409
5956   *
5957   * Returns:
5958   * {float} The approximate geodesic area of the polygon in square meters.
5959   */
5960  getGeodesicArea: function(projection) {
5961    var area = 0.0;
5962    if(this.components && (this.components.length > 0)) {
5963      area += Math.abs(this.components[0].getGeodesicArea(projection));
5964      for(var i=1, len=this.components.length; i<len; i++) {
5965          area -= Math.abs(this.components[i].getGeodesicArea(projection));
5966      }
5967    }
5968    return area;
5969  },
5970  /**
5971   * Method: containsPoint
5972   * Test if a point is inside a polygon.  Points on a polygon edge are
5973   *     considered inside.
5974   *
5975   * Parameters:
5976   * point - {<ZOO.Geometry.Point>}
5977   *
5978   * Returns:
5979   * {Boolean | Number} The point is inside the polygon.  Returns 1 if the
5980   *     point is on an edge.  Returns boolean otherwise.
5981   */
5982  containsPoint: function(point) {
5983    var numRings = this.components.length;
5984    var contained = false;
5985    if(numRings > 0) {
5986    // check exterior ring - 1 means on edge, boolean otherwise
5987      contained = this.components[0].containsPoint(point);
5988      if(contained !== 1) {
5989        if(contained && numRings > 1) {
5990          // check interior rings
5991          var hole;
5992          for(var i=1; i<numRings; ++i) {
5993            hole = this.components[i].containsPoint(point);
5994            if(hole) {
5995              if(hole === 1)
5996                contained = 1;
5997              else
5998                contained = false;
5999              break;
6000            }
6001          }
6002        }
6003      }
6004    }
6005    return contained;
6006  },
6007  intersects: function(geometry) {
6008    var intersect = false;
6009    var i, len;
6010    if(geometry.CLASS_NAME == "ZOO.Geometry.Point") {
6011      intersect = this.containsPoint(geometry);
6012    } else if(geometry.CLASS_NAME == "ZOO.Geometry.LineString" ||
6013              geometry.CLASS_NAME == "ZOO.Geometry.LinearRing") {
6014      // check if rings/linestrings intersect
6015      for(i=0, len=this.components.length; i<len; ++i) {
6016        intersect = geometry.intersects(this.components[i]);
6017        if(intersect) {
6018          break;
6019        }
6020      }
6021      if(!intersect) {
6022        // check if this poly contains points of the ring/linestring
6023        for(i=0, len=geometry.components.length; i<len; ++i) {
6024          intersect = this.containsPoint(geometry.components[i]);
6025          if(intersect) {
6026            break;
6027          }
6028        }
6029      }
6030    } else {
6031      for(i=0, len=geometry.components.length; i<len; ++ i) {
6032        intersect = this.intersects(geometry.components[i]);
6033        if(intersect)
6034          break;
6035      }
6036    }
6037    // check case where this poly is wholly contained by another
6038    if(!intersect && geometry.CLASS_NAME == "ZOO.Geometry.Polygon") {
6039      // exterior ring points will be contained in the other geometry
6040      var ring = this.components[0];
6041      for(i=0, len=ring.components.length; i<len; ++i) {
6042        intersect = geometry.containsPoint(ring.components[i]);
6043        if(intersect)
6044          break;
6045      }
6046    }
6047    return intersect;
6048  },
6049  distanceTo: function(geometry, options) {
6050    var edge = !(options && options.edge === false);
6051    var result;
6052    // this is the case where we might not be looking for distance to edge
6053    if(!edge && this.intersects(geometry))
6054      result = 0;
6055    else
6056      result = ZOO.Geometry.Collection.prototype.distanceTo.apply(
6057          this, [geometry, options]
6058          );
6059    return result;
6060  },
6061  CLASS_NAME: "ZOO.Geometry.Polygon"
6062});
6063/**
6064 * Method: createRegularPolygon
6065 * Create a regular polygon around a radius. Useful for creating circles
6066 * and the like.
6067 *
6068 * Parameters:
6069 * origin - {<ZOO.Geometry.Point>} center of polygon.
6070 * radius - {Float} distance to vertex, in map units.
6071 * sides - {Integer} Number of sides. 20 approximates a circle.
6072 * rotation - {Float} original angle of rotation, in degrees.
6073 */
6074ZOO.Geometry.Polygon.createRegularPolygon = function(origin, radius, sides, rotation) { 
6075    var angle = Math.PI * ((1/sides) - (1/2));
6076    if(rotation) {
6077        angle += (rotation / 180) * Math.PI;
6078    }
6079    var rotatedAngle, x, y;
6080    var points = [];
6081    for(var i=0; i<sides; ++i) {
6082        rotatedAngle = angle + (i * 2 * Math.PI / sides);
6083        x = origin.x + (radius * Math.cos(rotatedAngle));
6084        y = origin.y + (radius * Math.sin(rotatedAngle));
6085        points.push(new ZOO.Geometry.Point(x, y));
6086    }
6087    var ring = new ZOO.Geometry.LinearRing(points);
6088    return new ZOO.Geometry.Polygon([ring]);
6089};
6090/**
6091 * Class: ZOO.Geometry.MultiPolygon
6092 * MultiPolygon is a geometry with multiple <ZOO.Geometry.Polygon>
6093 * components.  Create a new instance with the <ZOO.Geometry.MultiPolygon>
6094 * constructor.
6095 *
6096 * Inherits from:
6097 *  - <ZOO.Geometry.Collection>
6098 */
6099ZOO.Geometry.MultiPolygon = ZOO.Class(
6100  ZOO.Geometry.Collection, {
6101  componentTypes: ["ZOO.Geometry.Polygon"],
6102  /**
6103   * Constructor: ZOO.Geometry.MultiPolygon
6104   * Create a new MultiPolygon geometry
6105   *
6106   * Parameters:
6107   * components - {Array(<ZOO.Geometry.Polygon>)} An array of polygons
6108   *              used to generate the MultiPolygon
6109   *
6110   */
6111  initialize: function(components) {
6112    ZOO.Geometry.Collection.prototype.initialize.apply(this,arguments);
6113  },
6114  CLASS_NAME: "ZOO.Geometry.MultiPolygon"
6115});
6116/**
6117 * Class: ZOO.Process
6118 * Used to query OGC WPS process defined by its URL and its identifier.
6119 * Usefull for chaining localhost process.
6120 */
6121ZOO.Process = ZOO.Class({
6122  /**
6123   * Property: schemaLocation
6124   * {String} Schema location for a particular minor version.
6125   */
6126  schemaLocation: "http://www.opengis.net/wps/1.0.0/../wpsExecute_request.xsd",
6127  /**
6128   * Property: namespaces
6129   * {Object} Mapping of namespace aliases to namespace URIs.
6130   */
6131  namespaces: {
6132    ows: "http://www.opengis.net/ows/1.1",
6133    wps: "http://www.opengis.net/wps/1.0.0",
6134    xlink: "http://www.w3.org/1999/xlink",
6135    xsi: "http://www.w3.org/2001/XMLSchema-instance",
6136  },
6137  /**
6138   * Property: url
6139   * {String} The OGC's Web PRocessing Service URL,
6140   *          default is http://localhost/zoo.
6141   */
6142  url: 'http://localhost/zoo',
6143  /**
6144   * Property: identifier
6145   * {String} Process identifier in the OGC's Web Processing Service.
6146   */
6147  identifier: null,
6148  /**
6149   * Constructor: ZOO.Process
6150   * Create a new Process
6151   *
6152   * Parameters:
6153   * url - {String} The OGC's Web Processing Service URL.
6154   * identifier - {String} The process identifier in the OGC's Web Processing Service.
6155   *
6156   */
6157  initialize: function(url,identifier) {
6158    this.url = url;
6159    this.identifier = identifier;
6160  },
6161  /**
6162   * Method: Execute
6163   * Query the OGC's Web PRocessing Servcie to Execute the process.
6164   *
6165   * Parameters:
6166   * inputs - {Object}
6167   *
6168   * Returns:
6169   * {String} The OGC's Web processing Service XML response. The result
6170   *          needs to be interpreted.
6171   */
6172  Execute: function(inputs,outputs) {
6173    if (this.identifier == null)
6174      return null;
6175    var body = new XML('<wps:Execute service="WPS" version="1.0.0" xmlns:wps="'+this.namespaces['wps']+'" xmlns:ows="'+this.namespaces['ows']+'" xmlns:xlink="'+this.namespaces['xlink']+'" xmlns:xsi="'+this.namespaces['xsi']+'" xsi:schemaLocation="'+this.schemaLocation+'"><ows:Identifier>'+this.identifier+'</ows:Identifier>'+this.buildDataInputsNode(inputs)+this.buildDataOutputsNode(outputs)+'</wps:Execute>');
6176    body = body.toXMLString();
6177    var headers=['Content-Type: text/xml; charset=UTF-8'];
6178      if(arguments.length>2){
6179        headers[headers.length]=arguments[2];
6180      }
6181    var response = ZOO.Request.Post(this.url,body,headers);
6182    return response;
6183  },
6184  buildOutput:{
6185    /**
6186     * Method: buildOutput.ResponseDocument
6187     * Given an E4XElement representing the WPS ResponseDocument output.
6188     *
6189     * Parameters:
6190     * identifier - {String} the input indetifier
6191     * data - {Object} A WPS complex data input.
6192     *
6193     * Returns:
6194     * {E4XElement} A WPS Input node.
6195     */
6196    'ResponseDocument': function(identifier,obj) {
6197      var output = new XML('<wps:ResponseForm xmlns:wps="'+this.namespaces['wps']+'"><wps:ResponseDocument><wps:Output'+(obj["mimeType"]?' mimeType="'+obj["mimeType"]+'" ':'')+(obj["encoding"]?' encoding="'+obj["encoding"]+'" ':'')+(obj["asReference"]?' asReference="'+obj["asReference"]+'" ':'')+'><ows:Identifier xmlns:ows="'+this.namespaces['ows']+'">'+identifier+'</ows:Identifier></wps:Output></wps:ResponseDocument></wps:ResponseForm>');
6198      if (obj.encoding)
6199        output.*::Data.*::ComplexData.@encoding = obj.encoding;
6200      if (obj.schema)
6201        output.*::Data.*::ComplexData.@schema = obj.schema;
6202      output = output.toXMLString();
6203      return output;
6204    },
6205    'RawDataOutput': function(identifier,obj) {
6206      var output = new XML('<wps:ResponseForm xmlns:wps="'+this.namespaces['wps']+'"><wps:RawDataOutput '+(obj["mimeType"]?' mimeType="'+obj["mimeType"]+'" ':'')+(obj["encoding"]?' encoding="'+obj["encoding"]+'" ':'')+'><ows:Identifier xmlns:ows="'+this.namespaces['ows']+'">'+identifier+'</ows:Identifier></wps:RawDataOutput></wps:ResponseForm>');
6207      if (obj.encoding)
6208        output.*::Data.*::ComplexData.@encoding = obj.encoding;
6209      if (obj.schema)
6210        output.*::Data.*::ComplexData.@schema = obj.schema;
6211      output = output.toXMLString();
6212      return output;
6213    }
6214
6215  },
6216  /**
6217   * Property: buildInput
6218   * Object containing methods to build WPS inputs.
6219   */
6220  buildInput: {
6221    /**
6222     * Method: buildInput.complex
6223     * Given an E4XElement representing the WPS complex data input.
6224     *
6225     * Parameters:
6226     * identifier - {String} the input indetifier
6227     * data - {Object} A WPS complex data input.
6228     *
6229     * Returns:
6230     * {E4XElement} A WPS Input node.
6231     */
6232    'complex': function(identifier,data) {
6233      var input = new XML('<wps:Input xmlns:wps="'+this.namespaces['wps']+'"><ows:Identifier xmlns:ows="'+this.namespaces['ows']+'">'+identifier+'</ows:Identifier>'+(data.value?'<wps:Data><wps:ComplexData><![CDATA['+data.value+']]></wps:ComplexData></wps:Data>':(data.xlink?'<wps:Reference xmlns:xlink="'+this.namespaces['xlink']+'" xlink:href="'+data.xlink+'" mimeType="'+data.mimeType+'" />':''))+'</wps:Input>');
6234      if(data.xlink)
6235        input.*::Reference.@mimeType = data.mimetype ? data.mimetype : 'application/json';
6236      else
6237        input.*::Data.*::ComplexData.@mimeType = data.mimetype ? data.mimetype : 'application/json';
6238      if (data.encoding)
6239        input.*::Data.*::ComplexData.@encoding = data.encoding;
6240      if (data.schema)
6241        input.*::Data.*::ComplexData.@schema = data.schema;
6242      input = input.toXMLString();
6243      return input;
6244    },
6245    /**
6246     * Method: buildInput.reference
6247     * Given an E4XElement representing the WPS reference input.
6248     *
6249     * Parameters:
6250     * identifier - {String} the input indetifier
6251     * data - {Object} A WPS reference input.
6252     *
6253     * Returns:
6254     * {E4XElement} A WPS Input node.
6255     */
6256    'reference': function(identifier,data) {
6257      return '<wps:Input xmlns:wps="'+this.namespaces['wps']+'"><ows:Identifier xmlns:ows="'+this.namespaces['ows']+'">'+identifier+'</ows:Identifier><wps:Reference xmlns:xlink="'+this.namespaces['xlink']+'" xlink:href="'+data.value.replace('&','&amp;','gi')+'"/></wps:Input>';
6258    },
6259    /**
6260     * Method: buildInput.literal
6261     * Given an E4XElement representing the WPS literal data input.
6262     *
6263     * Parameters:
6264     * identifier - {String} the input indetifier
6265     * data - {Object} A WPS literal data input.
6266     *
6267     * Returns:
6268     * {E4XElement} The WPS Input node.
6269     */
6270    'literal': function(identifier,data) {
6271        if(data && !eval(data["isArray"])){
6272            var input = new XML('<wps:Input xmlns:wps="'+this.namespaces['wps']+'"><ows:Identifier xmlns:ows="'+this.namespaces['ows']+'">'+identifier+'</ows:Identifier><wps:Data><wps:LiteralData>'+data.value+'</wps:LiteralData></wps:Data></wps:Input>');
6273      if (data.type)
6274        input.*::Data.*::LiteralData.@dataType = data.type;
6275      if (data.uom)
6276        input.*::Data.*::LiteralData.@uom = data.uom;
6277      input = input.toXMLString();
6278      return input;
6279        }else if(data){
6280            var inputf="";
6281            for(i=0;i<parseInt(data["length"]);i++){
6282                var input = new XML('<wps:Input xmlns:wps="'+this.namespaces['wps']+'"><ows:Identifier xmlns:ows="'+this.namespaces['ows']+'">'+identifier+'</ows:Identifier><wps:Data><wps:LiteralData>'+data.value[i]+'</wps:LiteralData></wps:Data></wps:Input>');
6283                if (data.type)
6284                    input.*::Data.*::LiteralData.@dataType = data.type;
6285                if (data.uom)
6286                    input.*::Data.*::LiteralData.@uom = data.uom;
6287                inputf += input.toXMLString();
6288            }
6289            return inputf;
6290        }
6291       
6292    }
6293  },
6294  /**
6295   * Method: buildDataInputsNode
6296   * Method to build the WPS DataInputs element.
6297   *
6298   * Parameters:
6299   * inputs - {Object}
6300   *
6301   * Returns:
6302   * {E4XElement} The WPS DataInputs node for Execute query.
6303   */
6304  buildDataInputsNode:function(inputs){
6305    var data, builder, inputsArray=[];
6306    for (var attr in inputs) {
6307      data = inputs[attr];
6308        if (data && (data.mimetype || data.type == 'complex'))
6309        builder = this.buildInput['complex'];
6310        else if (data && (data.type == 'reference' || data.type == 'url'))
6311        builder = this.buildInput['reference'];
6312      else
6313        builder = this.buildInput['literal'];
6314      inputsArray.push(builder.apply(this,[attr,data]));
6315    }
6316    return '<wps:DataInputs xmlns:wps="'+this.namespaces['wps']+'">'+inputsArray.join('\n')+'</wps:DataInputs>';
6317  },
6318
6319  buildDataOutputsNode:function(outputs){
6320    var data, builder, outputsArray=[];
6321    for (var attr in outputs) {
6322      data = outputs[attr];
6323      builder = this.buildOutput[data.type];
6324      outputsArray.push(builder.apply(this,[attr,data]));
6325    }
6326    return outputsArray.join('\n');
6327  },
6328
6329  CLASS_NAME: "ZOO.Process"
6330});
Note: See TracBrowser for help on using the repository browser.

Search

ZOO Sponsors

http://www.zoo-project.org/trac/chrome/site/img/geolabs-logo.pnghttp://www.zoo-project.org/trac/chrome/site/img/neogeo-logo.png http://www.zoo-project.org/trac/chrome/site/img/apptech-logo.png http://www.zoo-project.org/trac/chrome/site/img/3liz-logo.png http://www.zoo-project.org/trac/chrome/site/img/gateway-logo.png

Become a sponsor !

Knowledge partners

http://www.zoo-project.org/trac/chrome/site/img/ocu-logo.png http://www.zoo-project.org/trac/chrome/site/img/gucas-logo.png http://www.zoo-project.org/trac/chrome/site/img/polimi-logo.png http://www.zoo-project.org/trac/chrome/site/img/fem-logo.png http://www.zoo-project.org/trac/chrome/site/img/supsi-logo.png http://www.zoo-project.org/trac/chrome/site/img/cumtb-logo.png

Become a knowledge partner

Related links

http://zoo-project.org/img/ogclogo.png http://zoo-project.org/img/osgeologo.png