GDAL读写shp文件

16 篇文章 6 订阅
GDAL读shp文件
(1) 注册所有的文件格式驱动
1 GDALAllRegister();
2 OGRRegisterAll();
(2)得到shp文件的处理器
1 OGRSFDriver* poDriver = Registrar::GetRegistrar()->GetDriverByName("ESRI Shapefile");
(3)打开shp文件
1 OGRDataSource* poDS = poDriver->Open( "D:\\lakes.shp", NULL );
(4)获取shp图层
1 OGRLayer* poLayer = poDS->GetLayer(0);
(5)读取几何和属性值
 1 OGRFeature * pFeature;
 2  while ((pFeature=poLayer->GetNextFeature())!=NULL)
 3  {
 4    OGRGeometry* pGeometry = pFeature->GetGeometryRef();
 5    if (pGeometry == NULL)
 6    {
 7        AfxMessageBox("Geometry get failed.");
 8        return FALSE;
 9    }
10  
11    OGRwkbGeometryType geoType = pGeometry->getGeometryType();
12    if (wkbPoint==geoType)
13      CString strNodeID = pFeature->GetFieldAsString("NodeID");
14    else if (wkbLineString==geoType)
15    {
16        OGRLineString* pLineGeo = (OGRLineString*)pGeometry;
17        double staX = pLineGeo->getX(0);
18        double staY = pLineGeo->getY(0);
19    }
20 }
(6)资源清理
1 OGRDataSource::DestroyDataSource( poDS );
2 OGRCleanupAll();
GDAL写shp文件
(1) 注册所有的文件格式驱动
1 GDALAllRegister();
2 OGRRegisterAll();
(2)得到shp文件的处理器
1 OGRSFDriver* poDriver = Registrar::GetRegistrar()->GetDriverByName("ESRI Shapefile");
(3)创建shp文件
1 OGRDataSource* poDS = poDriver->CreateDataSource( "D:\\lakes.shp", NULL );
(4)创建图层
OGRLayer* poLayer= poDS->CreateLayer( "tbLine", NULL, wkbLineString, NULL );
(5)创建字段
 1 // 字符串
 2  OGRFieldDefn oField1("GeoObjNum",OFTString);
 3 oField1.SetWidth(8);
 4  if( poLayer->CreateField( &oField1 ) != OGRERR_NONE ){
 5    AfxMessageBox( "Creating Name field failed.\n" );return FALSE;}
 6
 7  // 浮点数
 8  OGRFieldDefn oField2("LBTG",OFTReal);
 9 oField2.SetPrecision(3);
10  if( poLayer->CreateField( &oField2 ) != OGRERR_NONE ){
11    AfxMessageBox( "Creating Name field failed.\n" );return FALSE;}
12
13  // 整型
14  OGRFieldDefn oField3("Number",OFTInteger);
15  if( poLayer->CreateField( &oField3 ) != OGRERR_NONE ){
16    AfxMessageBox( "Creating Name field failed.\n" );return FALSE;}
(6)创建几何和Feature
 1 GRFeature *poFeature;
 2 poFeature = new OGRFeature( poLayer->GetLayerDefn() );
 3
 4 poFeature->SetField( "GeoObjNum", strGeoObjNum );
 5 poFeature->SetField( "LBTG", fLBTG );
 6 poFeature->SetField( "Number", number );
 7
 8 OGRLineString *poLine = new OGRLineString();
 9        
10 poLine->setNumPoints(2);
11 poLine->setPoint(0,startX,startY, 0.0);
12 poLine->setPoint(1,endX,endY, 0.0);
13            
14 poFeature->SetGeometryDirectly( poLine );
15  if( poLayer->CreateFeature( poFeature ) != OGRERR_NONE )
16 {
17     AfxMessageBox("Failed to create feature in shapefile.");
18     return FALSE;
19 }
(7)资源清理
1 OGRDataSource::DestroyDataSource( poDS );
2 OGRCleanupAll();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值