先看效果
代码:
#include <drogon/drogon.h>
#include <gdal_priv.h>
#include <string>
#include <iostream>
#include <fstream>
#include <cmath>
#include <vector>
#include <map>
#include <ogr_geometry.h> //Geometry对象
#include <ogr_spatialref.h> //Spatial Reference
#include <ogr_feature.h> //Feature Class Definition
#include <ogrsf_frmts.h> //Layer\DataSource\Drivers
#include <ogr_api.h>
#include <hiredis/hiredis.h>
using namespace std;
int TestPolygonShp() {
CPLSetConfigOption("GDAL_FILENAME_IS_UTF8", "NO");
CPLSetConfigOption("SHAPE_ENCODING", "UTF-8");
GDALAllRegister();
GDALDriver* shpDriver = GetGDALDriverManager()->GetDriverByName("ESRI Shapefile");
if (shpDriver == NULL) {
printf("%s\n", "ESRI Shapefile驱动创建失败!");
return 0;
}
GDALDataset* gdalDataSet = shpDriver->Create("..\\shp\\TestPolygon.shp", 0, 0, 0, GDT_Unknown, NULL);
OGRSpatialReference osr;
if (osr.importFromEPSG(4326) != OGRERR_NONE) {
printf("%s\n", "坐标系创建失败!");
return -1;
}
char** papszOptions = NULL;
papszOptions = CSLSetNameValue(papszOptions, "ENCODING", "UTF-8");
OGRLayer* regLayer = gdalDataSet->CreateLayer("regionLyr", &osr, wkbPolygon, papszOptions);
OGRFieldDefn regIdField("REG_ID", OFTInteger);
regIdField.SetWidth(8);
regLayer->CreateField(®IdField);
OGRFieldDefn regNameField("REG_NAME", OFTString);
regNameField.SetWidth(8);
regLayer->CreateField(®NameField);
OGRFeature* ogrFeature = OGRFeature::CreateFeature(regLayer->GetLayerDefn());
ogrFeature->SetField("REG_ID", 10001);
ogrFeature->SetField("REG_NAME", "军事禁区");
OGRPolygon ogrPolygon;
OGRLinearRing ogrLRout;
ogrLRout.addPoint(0.0, 0.0);
ogrLRout.addPoint(8.0, 0.0);
ogrLRout.addPoint(8.0, 8.0);
ogrLRout.addPoint(0.0, 8.0);
ogrLRout.addPoint(0.0, 0.0);
ogrPolygon.addRing(&ogrLRout);
OGRLinearRing ogrLRinI;
ogrLRinI.addPoint(1.0, 1.0);
ogrLRinI.addPoint(4.0, 1.0);
ogrLRinI.addPoint(3.0, 3.0);
ogrLRinI.addPoint(1.0, 1.0);
ogrPolygon.addRing(&ogrLRinI);
OGRLinearRing ogrLRinII;
ogrLRinII.addPoint(6.0, 3.0);
ogrLRinII.addPoint(5.0, 3.0);
ogrLRinII.addPoint(5.0, 6.0);
ogrLRinII.addPoint(6.0, 3.0);
ogrPolygon.addRing(&ogrLRinII);
ogrFeature->SetGeometry(&ogrPolygon);
regLayer->CreateFeature(ogrFeature);
OGRFeature::DestroyFeature(ogrFeature);
GDALClose(gdalDataSet);
return 0;
}
int main(){
TestPolygonShp();
}