C++代码如下:
#include "gdal_priv.h"
#include "ogrsf_frmts.h"
#include "ogr_geometry.h"
struct PointCloud3d
{
double x,y,z;
}
//形参filePath:生成的shapfile文件全路径,形如:"C:\\Users\\gm\\Desktop\\tree.shp"
bool CreatePointShpFile(const string& filePath, const QList<PointCloud3d>& points)
{
int pointCount = points.size();
if (!pointCount)
{
std::cout << "输入点云为空\n";
return false;
}
const char* pszDriverName = "ESRI Shapefile";
GDALDriver* poDriver = nullptr;
GDALDataset* poDataset = nullptr;
OGRLayer* poLayer = nullptr;
GDALAllRegister(); //注册GDAL库各种驱动
poDriver = GetGDALDriverManager()->GetDriverByName(pszDriverName);
if (poDriver == NULL)
{
return false;
}
//String转const char*
poDataset = poDriver->Create(filePath.c_str(), 9999, 9999, 0, GDT_Unknown, NULL);
if (poDataset == NULL)
{
return false;
}
//点图层:ekbPoint;面图层:wkbPolygon
//若CreateLayer成员函数的第三个参数为NULL,表示生成的点图层不存在地理空间参考。
poLayer = poDataset->CreateLayer("point_out", NULL, wkbPoint, NULL);
if (poLayer == NULL)
{
return false;
}
//点图层的属性字段:ID、X、Y、Z
//属性字段名称避免使用中文字符,否则会出问题!
OGRFieldDefn idField("ID", OFTInteger); //OFTInteger:整型数据
OGRFieldDefn xField("X", OFTReal); //OFTReal:双精度型数据
OGRFieldDefn yField("Y", OFTReal);
OGRFieldDefn zField("Z", OFTReal);
poLayer->CreateField(&idField);
poLayer->CreateField(&xField);
poLayer->CreateField(&yField);
poLayer->CreateField(&zField);
//属性字段写入值
OGRFeature *poFeature = OGRFeature::CreateFeature(poLayer->GetLayerDefn());
for (int i = 0; i < pointCount; ++i)
{
const PointCloud3d& p = points.at(i);
poFeature->SetField("ID", i);
poFeature->SetField("X", p.x);
poFeature->SetField("Y", p.y);
poFeature->SetField("Z", p.z);
OGRPoint pt;
pt.setX(p.x);
pt.setY(p.y);
pt.setZ(p.z);
poFeature->SetGeometry(&pt);
if (poLayer->CreateFeature(poFeature) != OGRERR_NONE)
{
std::cout << "失败!\n";
return false;
}
}
OGRFeature::DestroyFeature(poFeature);
GDALClose(poDataset);
return true;
}