Guest User

QGIS Core Centroid

a guest
Mar 29th, 2012
99
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* /src/core/qgscentralpointpositionmanager.cpp */
  2. int QgsCentralPointPositionManager::calculatePolygonCentroid( double x[], double y[], int numberOfPoints, double& centroidX, double& centroidY ) const
  3. {
  4.   register int i, j;
  5.   double ai, atmp = 0, xtmp = 0, ytmp = 0;
  6.   if ( numberOfPoints < 3 )
  7.   {
  8.     return 1;
  9.   }
  10.  
  11.   for ( i = numberOfPoints - 1, j = 0; j < numberOfPoints; i = j, j++ )
  12.   {
  13.     ai = x[i] * y[j] - x[j] * y[i];
  14.     atmp += ai;
  15.     xtmp += ( x[j] + x[i] ) * ai;
  16.     ytmp += ( y[j] + y[i] ) * ai;
  17.   }
  18.   if ( atmp == 0 )
  19.   {
  20.     return 2;
  21.   }
  22.   centroidX = xtmp / ( 3 * atmp );
  23.   centroidY = ytmp / ( 3 * atmp );
  24.   return 0;
  25. }
  26.  
  27.  
  28.  
  29. /* /src/core/pal/pointset.cpp */
  30.   void PointSet::getCentroid( double &px, double &py )
  31.   {
  32.     // for explanation see this page:
  33.     // http://local.wasp.uwa.edu.au/~pbourke/geometry/polyarea/
  34.  
  35.     int i, j;
  36.     double cx = 0, cy = 0, A = 0, tmp;
  37.     for ( i = 0; i < nbPoints; i++ )
  38.     {
  39.       j = i + 1; if ( j == nbPoints ) j = 0;
  40.       tmp = ( x[i] * y[j] - x[j] * y[i] );
  41.       cx += ( x[i] + x[j] ) * tmp;
  42.       cy += ( y[i] + y[j] ) * tmp;
  43.       A += tmp;
  44.     }
  45.  
  46.     px = cx / ( 3 * A );
  47.     py = cy / ( 3 * A );
  48.   }
RAW Paste Data