Fix memory in QuadEdgeSubdivision (#604)
[geos.git] / src / algorithm / CentroidLine.cpp
blob1c966dc122a4d913e2f520ca28669c64379da2c7
1 /**********************************************************************
3 * GEOS - Geometry Engine Open Source
4 * http://geos.osgeo.org
6 * Copyright (C) 2001-2002 Vivid Solutions Inc.
7 * Copyright (C) 2005 Refractions Research Inc.
9 * This is free software; you can redistribute and/or modify it under
10 * the terms of the GNU Lesser General Public Licence as published
11 * by the Free Software Foundation.
12 * See the COPYING file for more information.
14 **********************************************************************
16 **********************************************************************/
18 #include <geos/algorithm/CentroidLine.h>
19 #include <geos/geom/Coordinate.h>
20 #include <geos/geom/CoordinateSequence.h>
21 #include <geos/geom/Geometry.h>
22 #include <geos/geom/GeometryCollection.h>
23 #include <geos/geom/LineString.h>
25 #include <typeinfo>
27 using namespace geos::geom;
29 namespace geos {
30 namespace algorithm { // geos.algorithm
32 /*public*/
33 void
34 CentroidLine::add(const Geometry *geom)
36 const LineString* ls = dynamic_cast<const LineString*>(geom);
37 if ( ls )
39 add(ls->getCoordinatesRO());
40 return;
43 const GeometryCollection* gc = dynamic_cast<const GeometryCollection*>(geom);
44 if (gc)
46 for(std::size_t i=0, n=gc->getNumGeometries(); i<n; i++) {
47 add(gc->getGeometryN(i));
52 /*public*/
53 void
54 CentroidLine::add(const CoordinateSequence *pts)
56 std::size_t const npts=pts->getSize();
58 for(std::size_t i=1; i<npts; ++i)
60 const Coordinate &p1=pts->getAt(i-1);
61 const Coordinate &p2=pts->getAt(i);
63 double segmentLen=p1.distance(p2);
64 totalLength+=segmentLen;
65 double midx=(p1.x+p2.x)/2;
66 centSum.x+=segmentLen*midx;
67 double midy=(p1.y+p2.y)/2;
68 centSum.y+=segmentLen*midy;
72 Coordinate *
73 CentroidLine::getCentroid() const
75 return new Coordinate(centSum.x/totalLength, centSum.y/totalLength);
78 bool
79 CentroidLine::getCentroid(Coordinate& c) const
81 if ( totalLength == 0.0 ) return false;
82 c=Coordinate(centSum.x/totalLength, centSum.y/totalLength);
83 return true;
86 } // namespace geos.algorithm
87 } // namespace geos