创建点文件

创建shp文件

#include "ogrsf_ftmts.h"
#include<vector>
#include<random>
#include "ogr_srs_api.h"

void Writing2Shp(const char *output_shp){
    GDALAllRegister();//注册所有可用的驱动程序
    const char *pszName = "ESRI Shapefile"; //提前设置shp文件格式,后面可以用GetDriverByName()函数适配

    GDALDriver *poDriver;
    poDriver = GetGDALDriverManager()->GetDriverByName(pszDriverName);//根据前面的设置打开shp驱动
    //判断驱动是否打开
     if (poDriver == NULL)
    {
        printf("%s driver not available.\n", pszDriverName);
        exit(1);
    }
    //设置数据源Create(const char *pszName, int nXSize, int nYSize, int nBands, GDALDataType eType, CSLConstList papszOptions)
    GDALDataset *poDS = poDriver->Create("自定义shp文件名称,别忘了加shp后缀",0,0,0,GDT_Unknow,NULL);
    //判断数据源是否创建成功
     if (poDS == NULL)
    {
        printf("Creation of output file failed.\n");
        exit(1);
    }
}

定义shp文件属性

//接下来依次创建图层,几何要素,坐标系,属性,几何
OGRLayer* poLayer;  //创建图层

//设置坐标系,坐标系为EPSG4326,这是基于WGS-84椭球的地理坐标系,经纬度的单位为度
OGRSpatialReference oSRS;
oSRS.importFromEPSG(4326);
//CreateLayer(const char *pszName, const OGRSpatialReference *poSpatialRef = nullptr, OGRwkbGeometryType eGType = wkbUnknown, char **papszOptions = nullptr)这是GDALDataset::CreateLayer()函数的参数
poLayer = poDS->CreateLayer("自定义图层名称", &oSRS, wkbPoint, NULL);
if (poLayer == NULL)
{
    printf("Layer creation failed.\n");
    exit(1);
}
//定义属性字段,这里依次定义了三个字段,分别是ID,X,Y
OGRFieldDefn oField1("Id", OFTInteger);
oField1.SetWidth(2);
if (poLayer->CreateField(&oField1) != OGRERR_NONE)
{
    printf("Creating Id field failed.\n");
    exit(1);
}
OGRFieldDefn oField2("X", OFTReal);
oField2.SetPrecision(2);
if (poLayer->CreateField(&oField2) != OGRERR_NONE)
{
    printf("Creating X field failed.\n");
    exit(1);
}
OGRFieldDefn oField3("Y", OFTReal);
oField3.SetPrecision(2);
if (poLayer->CreateField(&oField3) != OGRERR_NONE)
{
    printf("Creating Y field failed.\n");
    exit(1);
}

随机生成五十个点

std::vector<double> x;
std::vector<double> y;

std::default_random_engine generator;
std::uniform_real_distribution<double> distribution(0.0, 100.0);
for (int i = 0; i < 50; i++) {
    x.push_back(distribution(generator));
    y.push_back(distribution(generator));
    OGRFeature* poFeature;

    poFeature = OGRFeature::CreateFeature(poLayer->GetLayerDefn());
    poFeature->SetField("Id", i+1);
    poFeature->SetField("X", x[i]);
    poFeature->SetField("Y", y[i]);
    OGRPoint pt;

    pt.setX(x[i]);
    pt.setY(y[i]);

    poFeature->SetGeometry(&pt);

    if (poLayer->CreateFeature(poFeature) != OGRERR_NONE)
    {
        printf("Failed to create feature in shapefile.\n");
        exit(1);
    }

    OGRFeature::DestroyFeature(poFeature);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值