可可西

GDAL读写shp文件

#include "gdal_include/gdal.h"

#include "gdal_include/ogr_api.h"
#include "gdal_include/ogrsf_frmts.h"

#pragma comment(lib, "lib/gdal_i.lib")

-----------------------------------------

GDAL读shp文件

(1) 注册所有的文件格式驱动

1 GDALAllRegister();
2 OGRRegisterAll();

(2)得到shp文件的处理器

1 OGRSFDriver* poDriver = OGRSFDriverRegistrar::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 = OGRSFDriverRegistrar::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 OGRFeature *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();

posted on 2011-05-16 14:11  可可西  阅读(12647)  评论(0编辑  收藏  举报

导航