使用开源GIS类库GDAL/OGR读写shaple文件的一些代码片段

Python与开源GIS

使用开源GIS类库GDAL/OGR读写shaple文件的一些代码片段

2016-12-08 作者: xuzhiping 浏览: 2680 次

摘要: 下面是在C++中使用开源GIS类库GDAL/OGR读写shaple文件的一些代码片段 GDAL读shp文件 (1) 注册所有的文件格式驱动 GDALAllRegister(); OGRRegisterAll(); (2)得到shp文件的处理器 OGRSFDr...

下面是在C++中使用开源GIS类库GDAL/OGR读写shaple文件的一些代码片段

GDAL读shp文件

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

GDALAllRegister();

OGRRegisterAll();

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

OGRSFDriver* poDriver = Registrar::GetRegistrar()->GetDriverByName("ESRI Shapefile");

(3)打开shp文件

OGRDataSource* poDS = poDriver->Open( "D:\\lakes.shp", NULL );

(4)获取shp图层

OGRLayer* poLayer = poDS->GetLayer(0);

(5)读取几何和属性值

  OGRFeature * pFeature;
   while ((pFeature=poLayer->GetNextFeature())!=NULL)
   {
 OGRGeometry* pGeometry = pFeature->GetGeometryRef();
 if (pGeometry == NULL)
 {
AfxMessageBox("Geometry get failed.");
 return FALSE;
 }

OGRwkbGeometryType geoType = pGeometry->getGeometryType();
if (wkbPoint==geoType)
  CString strNodeID = pFeature->GetFieldAsString("NodeID");
else if (wkbLineString==geoType)
{
OGRLineString* pLineGeo = (OGRLineString*)pGeometry;
double staX = pLineGeo->getX(0);
double staY = pLineGeo->getY(0);
}
 }

6)资源清理

OGRDataSource::DestroyDataSource( poDS );
OGRCleanupAll();

GDAL写shp文件

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

 GDALAllRegister();
 OGRRegisterAll();

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

OGRSFDriver* poDriver = Registrar::GetRegistrar()->GetDriverByName("ESRI Shapefile");

(3)创建shp文件

OGRDataSource* poDS = poDriver->CreateDataSource( "D:\\lakes.shp", NULL );

(4)创建图层

OGRLayer* poLayer= poDS->CreateLayer( "tbLine", NULL, wkbLineString, NULL );

(5)创建字段

 // 字符串
   OGRFieldDefn oField1("GeoObjNum",OFTString);
  oField1.SetWidth(8);
   if( poLayer->CreateField( &oField1 ) != OGRERR_NONE ){
 AfxMessageBox( "Creating Name field failed.\n" );return FALSE;}

   // 浮点数
   OGRFieldDefn oField2("LBTG",OFTReal);
  oField2.SetPrecision(3);
 if( poLayer->CreateField( &oField2 ) != OGRERR_NONE ){
AfxMessageBox( "Creating Name field failed.\n" );return FALSE;}

  // 整型
  OGRFieldDefn oField3("Number",OFTInteger);
  if( poLayer->CreateField( &oField3 ) != OGRERR_NONE ){
AfxMessageBox( "Creating Name field failed.\n" );return FALSE;}

(6)创建几何和Feature

  GRFeature *poFeature;
  poFeature = new OGRFeature( poLayer->GetLayerDefn() );

  poFeature->SetField( "GeoObjNum", strGeoObjNum );
  poFeature->SetField( "LBTG", fLBTG );
  poFeature->SetField( "Number", number );

  OGRLineString *poLine = new OGRLineString();

 poLine->setNumPoints(2);
 poLine->setPoint(0,startX,startY, 0.0);
 poLine->setPoint(1,endX,endY, 0.0);

 poFeature->SetGeometryDirectly( poLine ); 
  if( poLayer->CreateFeature( poFeature ) != OGRERR_NONE )
 {
 AfxMessageBox("Failed to create feature in shapefile.");
 return FALSE;
 }

(7)资源清理

 OGRDataSource::DestroyDataSource( poDS );
 OGRCleanupAll();

关注“开源集思”公众号
获取免费资源

随机推荐


Copyright © 2014-2019 OSGeo中国中心 吉ICP备05002032号

Powered by TorCMS

OSGeo 中国中心 邮件列表

问题讨论 : 要订阅或者退订列表,请点击 订阅

发言 : 请写信给: osgeo-china@lists.osgeo.org