Wechat: yu389741| Email: gisdqy@163.com

Shop:https://www.giserdqy.com/shop

GDAL 获取多边形OGRPolygon的方法


GIS是一门很大的学问,就拿怎么在SHP文件中获得一个多边形来说,我看了很多的人的博客都是这样的:

OGRFeature *cityOutsideBuildingPoFeature;
while ((cityOutsideBuildingPoFeature = mLayer->GetNextFeature()) != NULL)
{
	OGRGeometry *rdPoGeometry = cityOutsideBuildingPoFeature->GetGeometryRef();
	if (rdPoGeometry != NULL)
	{
		OGRwkbGeometryType pGeoType = rdPoGeometry->getGeometryType();
		OGRPolygon *rdPolygon;
		if (pGeoType == wkbPolygon)//这里就是多边形判断
		{
			rdPolygon = (OGRPolygon*)rdPoGeometry->clone();
		}
		else if (pGeoType == wkbMultiPolygon)  //这里就是带空洞多边形判断
		{
			OGRMultiPolygon * multiPolygon = (OGRMultiPolygon *)rdPoGeometry;
			multiPolygon->closeRings();
			OGRGeometry *FirstGeometry = NULL;
			FirstGeometry = multiPolygon->getGeometryRef(0);
			rdPolygon = (OGRPolygon *)FirstGeometry;
		}
	}
	OGRFeature::DestroyFeature(cityOutsideBuildingPoFeature);
}

我觉得在获得多边形外轮廓时,感觉有点多余了,最终获得的也只是多个多边形中的第一个多边形而已,这不可能达到需求,那怎么获得整个多边形的多轮廓呢,如下:

OGRFeature *cityOutsideBuildingPoFeature;
while ((cityOutsideBuildingPoFeature = _mOCityBuildingLayerOper->mLayer->GetNextFeature()) != NULL)
{
	OGRGeometry *rdPoGeometry = cityOutsideBuildingPoFeature->GetGeometryRef();
	if (rdPoGeometry != NULL)
	{
		OGRwkbGeometryType pGeoType = rdPoGeometry->getGeometryType();
		OGRPolygon *rdPolygon;
		if (pGeoType == wkbPolygon)//这里就是多边形判断
		{
			rdPolygon = (OGRPolygon*)rdPoGeometry->clone();
		}
		else if (pGeoType == wkbMultiPolygon)  //这里就是带空洞多边形判断
		{
			OGRMultiPolygon * multiPolygon = (OGRMultiPolygon *)rdPoGeometry;
			int num = multiPolygon->getNumGeometries();

			rdPolygon = (OGRPolygon *)multiPolygon->getGeometryRef(0);
			for (int i = 1; i < num; i++)
			{
				OGRPolygon *mOGRPolygon = (OGRPolygon *)multiPolygon->getGeometryRef(i);
				rdPolygon = (OGRPolygon *)rdPolygon->Union(mOGRPolygon);
			}
		}	
	}
	OGRFeature::DestroyFeature(cityOutsideBuildingPoFeature);
}

由上代码可以看出,我们需要遍历wkbMultiPolygon,然后将所有多边形求并集,这样就可以获取到整个多边形的外轮廓了

转载自:https://blog.csdn.net/octdream/article/details/77468338