GDAl C++ 创建Shp
Posted Geography爱好者
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了GDAl C++ 创建Shp相关的知识,希望对你有一定的参考价值。
用于GDAL,C++开发环境测试。
#include <iostream> #include "gdal_priv.h" #include "ogrsf_frmts.h" #include "ogr_geometry.h" #pragma comment (lib,"C:\\warmerda\\bld\\lib\\gdal_i.lib") using namespace std; void CreateShapeFile() { const char *pszDriverName = "ESRI Shapefile"; OGRSFDriver *poDriver; OGRRegisterAll(); poDriver = OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName( pszDriverName ); if( poDriver == NULL ) { printf( "%s driver not available.\n", pszDriverName ); exit( 1 ); } OGRDataSource *poDS; poDS = poDriver->CreateDataSource( "point_out.shp", NULL ); if( poDS == NULL ) { printf( "Creation of output file failed.\n" ); exit( 1 ); } OGRLayer *poLayer; poLayer = poDS->CreateLayer( "point_out", NULL, wkbPoint, NULL ); if( poLayer == NULL ) { printf( "Layer creation failed.\n" ); exit( 1 ); } OGRFieldDefn oField( "Name", OFTString ); oField.SetWidth(32); if( poLayer->CreateField( &oField ) != OGRERR_NONE ) { printf( "Creating Name field failed.\n" ); exit( 1 ); } double x, y; char szName[33]; while( !feof(stdin) && fscanf( stdin, "%lf,%lf,%32s", &x, &y, szName ) == 3 ) { OGRFeature *poFeature; poFeature = new OGRFeature( poLayer->GetLayerDefn() ); poFeature->SetField( "Name", szName ); OGRPoint pt; pt.setX( x ); pt.setY( y ); poFeature->SetGeometry( &pt ); if( poLayer->CreateFeature( poFeature ) != OGRERR_NONE ) { printf( "Failed to create feature in shapefile.\n" ); exit( 1 ); } OGRFeature::DestroyFeature( poFeature ); } OGRDataSource::DestroyDataSource( poDS ); } int main() { //CreateShapeFile(); //cout<<"创建成功"<<endl; const char *pszDriverName="ESRI Shapefile"; OGRSFDriver *poDriver; OGRRegisterAll(); poDriver=OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(pszDriverName); if(poDriver==NULL) { cout<<"注册失败"<<endl; } OGRDataSource *poDS; poDS=poDriver->CreateDataSource("point_out.shp",NULL); if(poDS==NULL) { cout<<"创建驱动失败!"<<endl; } OGRLayer *poLayer; poLayer=poDS->CreateLayer("point_out",NULL,wkbPoint,NULL); if(poLayer==NULL) { cout<<"创建图层失败"<<endl; } OGRFieldDefn oField("Name",OFTString); oField.SetWidth(22); if(poLayer->CreateField(&oField)!=OGRERR_NONE) { cout<<"添加字段失败!"<<endl; } //下面从stdin中循环读取 “x,y,name”格式的点信息。 double x=0,y=100; char szName[33]; for(int a=0;a!=10;++a) { x+=a; y+=a; OGRFeature *poFeature; poFeature=new OGRFeature(poLayer->GetLayerDefn()); poFeature->SetField("Name",szName); OGRPoint pt; pt.setX(x); pt.setY(y); poFeature->SetGeometry(&pt); if(poLayer->CreateFeature(poFeature)!=OGRERR_NONE) { cout<<"创建要素失败"<<endl; } //OGRFeature::DestroyFeature(*poFeature);//创建一个feature.OGRLayer::CreateFeature() 只是重新复制了一个feature,因此操作完成后需要清除feature对象 } //最后释放datasoure资源,刷新所有写的操作 OGRDataSource::DestroyDataSource(poDS); cout<<"文件创建成功!"<<endl; return 0; }
以上是关于GDAl C++ 创建Shp的主要内容,如果未能解决你的问题,请参考以下文章