【GDAL】C++加载矢量数据

我的未来我决定 提交于 2020-12-23 12:43:54

【GDAL】C++加载矢量数据

注意事项:

1、加载和保存shp都需要的准备工作代码段:

CPLSetConfigOption("GDAL_FILENAME_IS_UTF8", "NO");	// 支持中文路径
CPLSetConfigOption("SHAPE_ENCODING", "");			//属性表支持中文字段

GDALAllRegister();

2、读shp:获得feature 的所需要用到的接口:
GDALDataset
OGRlayer、OGRFeatureDefn等。
关键代码:


GDALDataset* podataset = (GDALDataset*)GDALOpenEx(file_path_name, GDAL_OF_VECTOR, NULL,NULL, NULL);
	if (podataset == NULL) {
   
   
		cout << "open failed." << endl;
		return 0;
	}
	int layercount = podataset->GetLayerCount();
	OGRLayer* player = podataset->GetLayer(0);
	OGRFeatureDefn* pDefn = player->GetLayerDefn();
	player->ResetReading();
	pspatialreference=player->GetSpatialRef();
	OGREnvelope* pextent=new OGREnvelope();
	player->GetExtent(pextent);//pextent有minx,miny,maxx,maxy四个元素
	OGRFeature* pfeature;
	int num = 0;
	while ((pfeature = player->GetNextFeature()) != NULL)
	{
   
   
		OGRGeometry* pgeometry = pfeature->GetGeometryRef();
		SHP_RW geo;//定义的SHP_RW类
		geo.pgeometry = pgeometry;
		if (pgeometry != NULL)
		{
   
   
			auto geometrytype = wkbFlatten(pgeometry->getGeometryType());
			if (geometrytype == wkbPoint)
			{
   
   
				///点操作
			}
			else if (geometrytype == wkbLineString)
			{
   
   
				///线操作
			}
			else if (geometrytype == wkbPolygon)
			{
   
   
				///面操作
			}
			else
			{
   
   
				cout << "no geometry.";
			}
			OGRFeature::DestroyFeature(pfeature);
		}
	}

3、写SHP数据:
关键代码:

const char* pszDriverName = "ESRI Shapefile";
	GDALDriver* poDriver;
	poDriver = GetGDALDriverManager()->GetDriverByName(pszDriverName);
	if (poDriver == NULL)
	{
   
   
		cout << pszDriverName << " driver not available.\n";
		return 0;
	}
	//创建数据源
	GDALDataset* poDS;
	poDS = poDriver->Create(file_path_name, 0, 0, 0, GDT_Unknown, NULL); //创建shp文件
	if (poDS == NULL)
	{
   
   
		cout<<"Creation of output file failed.\n";
		return 0;
	}
poLayer = poDS->CreateLayer("point_out",pspatialreference, wkbPoint, NULL);//选择是否需要设置投影
write_shp.player = poLayer;//write_shp也是rw_shp的实例
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!