Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!
Guest

OL APIMethod: getCentroid

By: a guest on Mar 28th, 2012  |  syntax: JavaScript  |  size: 0.99 KB  |  views: 67  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. getCentroid: function() {
  2.     if (this.components) {
  3.         var len = this.components.length;
  4.         if (len > 0 && len <= 2) {
  5.             return this.components[0].clone();
  6.         } else if (len > 2) {
  7.             var sumX = 0.0;
  8.             var sumY = 0.0;
  9.             var averX = this.components[0].x;
  10.             var averY = this.components[0].y;
  11.             for (var i = 0; i < len - 1; i++) {
  12.                 var b = this.components[i];
  13.                 var c = this.components[i+1];
  14.                 sumX += (b.x + c.x - 2 * averX) * ((b.x - averX) * (c.y - averY) - (c.x - averX) * (b.y - averY));
  15.                 sumY += (b.y + c.y - 2 * averY) * ((b.x - averX) * (c.y - averY) - (c.x - averX) * (b.y - averY));
  16.             }
  17.             var area = -1 * this.getArea();
  18.             var x = averX + sumX / (6 * area);
  19.             var y = averY + sumY / (6 * area);
  20.             return new OpenLayers.Geometry.Point(x, y);
  21.         } else {
  22.             return null;
  23.         }
  24.     }
  25. },