GEOS库学习之四:几何关系判断

原理上一篇已经介绍过了,这篇就直接进行程序练习

#include "geos.h"

GeometryFactory factory;

//创建一条环线,与线的区别就是环线是闭合的。即第一个点和最后一点重合
LinearRing* createGeosRing(double x,double y,double offset)
{
     CoordinateArraySequenceFactory csf; 
    CoordinateSequence* cs = csf.create(6,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+2*offset,y+2*offset),3);
    cs->setAt(Coordinate(x+2*offset,y),4);
    cs->setAt(Coordinate(x,y),5); //与第一个点相等
    LinearRing *lr=factory.createLinearRing(cs);
    return lr;
}

//创建一个多边形,如果多边形内部没有孔洞实际上与环线是一样的
Polygon* createGeosPolygon(double x,double y,double offset)
{
    LinearRing *lr=createGeosRing(x,y,offset);
    Polygon *poly=factory.createPolygon(lr,NULL); //如果多边形中间没有孔洞,第二个参数设为NULL
    return poly;
}

int main()
{
       Polygon *p1=createGeosPolygon(12,12,5); //创建第一个多边形
    
    for(int i=0;i<=20;i++)
    {
        cout<<i<<":   ";
        Polygon *p2=createGeosPolygon(0,0,i); //创建第二个多边形
        IntersectionMatrix *im=p2->relate(p1);
        cout<<*im<<"    ";    //返回DE-9IM交叉矩阵
        if(p2->disjoint(p1))
            cout<<"不相交"<<endl;
        else
        {
            if(p2->touches(p1))
                cout<<"接触"<<endl;
            else if(p2->overlaps(p1))
                cout<<"部分重叠"<<endl;
            else if(p2->covers(p1))
                cout<<"覆盖"<<endl;
            else
                cout<<*im<<endl;
        }
    }
    system("pause");
    return 1;
}

结果如下:

原文地址:https://www.cnblogs.com/denny402/p/4968245.html