使用GDAL/OGR读取点、线矢量文件
GDAL中对矢量数据的读写操作都是基于OGR库,只要编译了GDAL库就可以使用OGR库,不用另外编译,但须添加相应的头文件#include “ogrsf_frmts.h”。我读取的文件为shp文件,shp文件只有一个图层,相对比较简单。对于点、线矢量文件,这里不只是if (wkbPoint==geotype)和if ( wkbLineString==geotype),还有multiPoint和multiLine类型,具体的读入到下一篇读取polygon时在说明。
////////////////////////////////获取图层
int iLayerCount=poSrcDS->GetLayerCount();
OGRLayer*poLayer=poSrcDS->GetLayer(0);
if (poLayer==NULL)
{
QMessageBox::information(this,tr(“Waring”), tr(“获取图层失败!”));
OGRDataSource::DestroyDataSource(poSrcDS);
return;
}
////////////////初始化图层
poLayer->ResetReading();
///////////////获取属性表表头信息
int iFeatureCount=poLayer->GetFeatureCount(); //获得要素个数
OGRSpatialReference *shp_spf;
shp_spf=poLayer->GetSpatialRef(); //获得矢量数据的投影信息
int PNum=0; //记录点的个数
int flag; //用于标记数据类型
vector<double> PointX; //用于存点数据
vector<double> PointY;
vector<int>LPointNum; //获取线状数据上线条个数
int LNum=0; //用于记录第几条线
vector<int>GPointNum;//获取多边形数据上多边形个数
int GNum=0; //记录第几个多边形
OGRFeatureDefn*poDefn=poLayer->GetLayerDefn();
int iFieldCount =poDefn->GetFieldCount();
for (int iAttr=0;iAttr<iFieldCount;iAttr++)
{
OGRFieldDefn*poField=poDefn->GetFieldDefn(iAttr);
/* cout<<poField->GetNameRef()<<“:”<<poField->GetFieldTypeName(poField->GetType())<<“(“<<poField->GetWidth()<<“,”<<poField->GetPrecision()<<“)”<<endl;*/
}
OGRFeature*poFeature=NULL;
//////遍历图层中的每个要素
while ((poFeature=poLayer->GetNextFeature())!=NULL)
{
///获取要素中的几何体
OGRGeometry*poGeometry=poFeature->GetGeometryRef();
OGRwkbGeometryType geotype;
geotype=poGeometry->getGeometryType(); //获取该文件类型,点状、线状or面状
OGRPoint *poPoint=NULL;
OGRLineString *poLine=NULL;
if (wkbPoint==geotype) //若该要素为点状
{
flag=1;
poPoint=(OGRPoint*)poGeometry;
PointX.push_back(poPoint->getX());
PointY.push_back(poPoint->getY());
poEnvelope=new OGREnvelope; //获取该要素的四至范围
poGeometry->getEnvelope(poEnvelope);
if(0==PNum)
{
minX=poEnvelope->MinX;
minY=poEnvelope->MinY;
maxX=poEnvelope->MaxX;
maxY=poEnvelope->MaxY;
PNum++;
}
else
{
if((poEnvelope->MinX)<minX) minX=poEnvelope->MinX;
if((poEnvelope->MinY)<minY) minY=poEnvelope->MinY;
if((poEnvelope->MaxX)>maxX) maxX=poEnvelope->MaxX;
if((poEnvelope->MaxY)>maxY) maxY=poEnvelope->MaxY;
PNum++;
}
}
if ( wkbLineString==geotype) //若该要素为线状
{
flag=2;
poLine=(OGRLineString*)poGeometry;
if (poLine->IsEmpty())
{
continue;
}
poEnvelope=new OGREnvelope; //获取该要素的四至范围
poGeometry->getEnvelope(poEnvelope);
if(0==LNum)
{
minX=poEnvelope->MinX;
minY=poEnvelope->MinY;
maxX=poEnvelope->MaxX;
maxY=poEnvelope->MaxY;
}
else
{
if((poEnvelope->MinX)<minX) minX=poEnvelope->MinX;
if((poEnvelope->MinY)<minY) minY=poEnvelope->MinY;
if((poEnvelope->MaxX)>maxX) maxX=poEnvelope->MaxX;
if((poEnvelope->MaxY)>maxY) maxY=poEnvelope->MaxY;
}
LPointNum.push_back(poLine->getNumPoints());
OGRRawPoint *Lpoints=new OGRRawPoint[LPointNum.at(LNum)];
poLine->getPoints(Lpoints,NULL);
for (int k=0;k<LPointNum.at(LNum);k++)
{
PointX.push_back(Lpoints[k].x);
PointY.push_back(Lpoints[k].y);
}
LNum++;
delete []Lpoints;
}
转载自:https://blog.csdn.net/guoqiong07/article/details/38295759