GDAL库在使用时又很多环境变量要提前设置,如果忽略这一步,代码会出现异常失败。本文由描述了静态和运行时两种设置方法供参考。
源码是OGR站点的示例改了一点点,如下。出错部分是红色加粗句,err一直为6。
#include "stdafx.h"
#include "cpl_conv.h"
#include <ogr_spatialref.h>
bool DoTransForm(int nCS1,int nCS2)
{
OGRSpatialReference oSourceSRS, oTargetSRS;
OGRCoordinateTransformation *poCT;
double x1, y1, x2, y2;
//设置环境变量
//CPLSetConfigOption( "GDAL_DATA", "d://gdal//data" );
OGRErr err = oSourceSRS.importFromEPSG( nCS1 );
oTargetSRS.importFromEPSG( nCS2 );
char *pszWKT = NULL;
//测试
oSourceSRS.exportToWkt(&pszWKT);
AfxMessageBox(CString(pszWKT));
//定义转化
poCT = OGRCreateCoordinateTransformation( &oSourceSRS,&oTargetSRS );
//x = atof( papszArgv[i+3] );
//y = atof( papszArgv[i+4] );
x1 = 100;y1 = 40;
x2 = x1; y2 = y1;
char msg[100];
if( poCT == NULL || !poCT->Transform( 1, &x2, &y2 ) )
AfxMessageBox((CString)("Transformation failed./n" ));
else
{
sprintf(msg, "(%f,%f) -> (%f,%f)/n",x1, y1, x2, y2 );
AfxMessageBox((CString)msg);
}
return true;
}
静态设置:我的电脑|属性|高级|环境变量|新建|GDAL_DATA="$GDAL/data"
运行时设置:再调用GDAL库开始处加CPLSetConfigOption( "GDAL_DATA", "d://gdal//data" );