您的位置:首页 > 其它

GEOS库的学习之二:简单几何图形的创建

2015-11-15 18:49 393 查看
几何图形(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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: