【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的实例
来源:oschina
链接:https://my.oschina.net/u/4360480/blog/4832613