幾何圖形(Geometry)是geos里面基本的操作對象,因此Geometry類就是最重要的一個類
幾何圖形中主要有三個要素:點,線,面。橫縱坐標構成點,多個點構成線,環線構成面,點線面混合構成幾何集合。對應的幾個類為
坐標:Coordinate
點:Point、MultiPoint
線:LineString、MultiLineString(多條線)、LinearRing(環線)
面:Polygon、MultiPolygon
集合:GeometryCollection
在geos中,最小的組成單位是坐標,由Coordinate類來創建,如:Coordinate(2,3),表示一個點,橫坐標是2,縱坐標是3.
所有的幾何圖形的創建,都是由類GeometryFactory來完成。因此,在創建幾何圖形前,可以先創建一個全局的GeometryFactory對象;
GeometryFactory factory; //全局對象,所有的圖形都由此對象創建
1、點的創建
Point* createGeosPoint(double x,double y) { Coordinate pt(x,y); Point* p=factory.createPoint(pt); return p; }
2、非閉合線條的創建
LineString* createGeosLine(double x,double y, double offset) { CoordinateArraySequence *cas=new CoordinateArraySequence(); //構建點序列 cas->add(Coordinate(x,y)); cas->add(Coordinate(x,y+offset)); cas->add(Coordinate(x+offset,y+offset)); cas->add(Coordinate(x+offset,y+2*offset)); cas->add(Coordinate(x+2*offset,y+2*offset)); LineString *ls=factory.createLineString(cas); return ls; }
3、閉合線條的創建
//創建一條環線,與線的區別就是環線是閉合的。即第一個點和最后一點重合 LinearRing* createGeosRing(double x,double y,double offset) { CoordinateArraySequence *cas=new CoordinateArraySequence(); //構建點序列 cas->add(Coordinate(x,y)); cas->add(Coordinate(x,y+offset)); cas->add(Coordinate(x+offset,y+offset)); cas->add(Coordinate(x+offset,y+2*offset)); cas->add(Coordinate(x+2*offset,y+2*offset)); cas->add(Coordinate(x+2*offset,y)); cas->add(Coordinate(x,y)); //與第一個點相等 LinearRing *lr=factory.createLinearRing(cas); return lr; }
除了用add的方法來構建點序列,也可以用另外一種方法setAt
LinearRing* createGeosRing(double x,double y,double offset) { CoordinateArraySequenceFactory csf; CoordinateSequence* cs = csf.create(7,2); cs->setAt(Coordinate(x,y),0); cs->setAt(Coordinate(x,y+offset),1); cs->setAt(Coordinate(x+offset,y+offset),2); cs->setAt(Coordinate(x+offset,y+2*offset),3); cs->setAt(Coordinate(x+2*offset,y+2*offset),4); cs->setAt(Coordinate(x+2*offset,y),5); cs->setAt(Coordinate(x,y),6); //與第一個點相等 LinearRing *lr=factory.createLinearRing(cs); return lr; }
4、多邊形的創建
//創建一個多邊形,如果多邊形內部沒有孔洞實際上與環線是一樣的 Polygon* createGeosPolygon(double x,double y,double offset) { LinearRing *lr=createGeosRing(x,y,offset); Polygon *poly=factory.createPolygon(lr,NULL); //如果多邊形中間沒有孔洞,第二個參數設為NULL return poly; }
測試:
#include "geos.h" int main() { LineString *ls=createGeosRing(10,10,5); cout<<"線條點數:"<<ls->getNumPoints()<<" 線條長度:"<<ls->getLength()<<endl; Polygon *poly=createGeosPolygon(10,10,5); cout<<"多邊形面積:"<<poly->getArea()<<endl; system("pause"); return 1; }