小白初学gdal,想用c++实现矢量点和面的clip操作,找到官网的说明如下:

我的代码块:
#include "pch.h"
#include "gdal_priv.h"
#include "ogrsf_frmts.h"
#include <iostream>
bool VectorIntersection(const char *pszSrcShp, const char *pszMethodShp, const char *pszDstShp, const char* pszFormat);
int main()
{
const char *pszSrcFile = "E:\\MyThesis\\HeNan\\henan.shp"; //原始文件
const char *pszMethodFile = "E:\\MyThesis\\SiChuan\\Sichuan.shp"; //用来clip的文件
const char *pszOutFile = "E:\\MyThesis\\union.shp"; //结果文件
VectorIntersection(pszSrcFile, pszMethodFile, pszOutFile, "ESRI Shapefile");
return 0;
}
bool VectorIntersection(const char *pszSrcShp, const char *pszMethodShp, const char *pszDstShp, const char* pszFormat)
{
GDALAllRegister();
CPLSetConfigOption("SHAPE_ENCODING", "");
CPLSetConfigOption("GDAL_FILENAME_IS_UTF8", "NO");
//读取数据
GDALDataset *poSrcDS;
poSrcDS = (GDALDataset*)GDALOpenEx(pszSrcShp, GDAL_OF_VECTOR, NULL, NULL, NULL);
if (poSrcDS == NULL)
{
printf("Open failed.\n");
exit(1);
}
GDALDataset *poMethodDS;
poMethodDS = (GDALDataset*)GDALOpenEx(pszMethodShp, GDAL_OF_VECTOR, NULL, NULL, NULL);
if (poMethodDS == NULL)
{
printf("Open failed.\n");
exit(1);
}
//使用Shapefile驱动
GDALDriver *poDriver;
poDriver = GetGDALDriverManager()->GetDriverByName(pszFormat);
if (poDriver == NULL)
{
printf("%s driver not available.\n", pszFormat);
exit(1);
}
//根据文件名创建shp文件
GDALDataset* poDstDS = poDriver->Create(pszDstShp, 0, 0, 0, GDT_Unknown, NULL);
if (poDstDS == NULL)
{
printf("Creation of output file failed.\n");
exit(1);
}
//获取图层
OGRLayer *poSrcLayer = poSrcDS->GetLayer(0);
if (poSrcLayer == NULL)
{
printf("Creation of layer failed.\n");
GDALClose(poSrcDS); //关闭文件
GDALClose(poMethodDS);
GDALClose(poDstDS);
exit(1);
}
OGRLayer *poMethodLayer = poMethodDS->GetLayer(0);
if (poMethodLayer == NULL)
{
printf("Creation of layer failed.\n");
GDALClose(poSrcDS); //关闭文件
GDALClose(poMethodDS);
GDALClose(poDstDS);
exit(1);
}
//定义空间参考与原始矢量数据相同并创建图层
OGRLayer *poDstLayer;
OGRSpatialReference *pSRS = poSrcLayer->GetSpatialRef();
poDstLayer = poDstDS->CreateLayer("NewLayer", pSRS, wkbPolygon, NULL);
if (poDstLayer == NULL)
{
printf("Creation of layer failed.\n");
GDALClose(poSrcDS); //关闭文件
GDALClose(poMethodDS);
GDALClose(poDstDS);
exit(1);
}
poSrcLayer->Union(poMethodLayer, poDstLayer, NULL, NULL, NULL);
GDALClose(poSrcDS); //关闭文件
GDALClose(poMethodDS);
GDALClose(poDstDS);
return true;
}
参考博客地址:https://blog.csdn.net/secyb/article/details/80246105