GDAL读取高程文件,获取经纬度点的高程

#include 
#include 
#include 

float read_elevation(const char* tifFileName, float lon, float lat) 
{	
	// 注册所有功能
	GDALAllRegister();

	// 打开文件
	GDALDatasetH hDS = GDALOpen(tifFileName, GA_ReadOnly);
	if (hDS == nullptr)
	{
		fprintf(stderr, "Can't open %s\n", tifFileName);
		return 0.0;
	}
	int iBand = 1;
	GDALRasterBandH hBand = GDALGetRasterBand(hDS, iBand);
	if (hBand == nullptr)
	{
		fprintf(stderr, "Can't get band\n");
		return 0.0;
	}
		
	//获取坐标变换系数
	double trans[6] = { 0 };
	if (GDALGetGeoTransform(hDS, trans) != CE_None)
	{
		fprintf(stderr, "cant not get geotransform");
		return 0.0;
	}

	//获取图像的尺寸
	//int nImgSizeX = GDALGetRasterXSize(hDS);
	//int nImgSizeY = GDALGetRasterYSize(hDS);

	// 根据像素坐标计算经纬度数
	// double xGeo = trans[0] + xLine * trans[1] + yLine * trans[2];
	// double yGeo = trans[3] + xLine * trans[4] + yLine * trans[5];

	// 计算像素位置
	double dTemp = trans[2] * trans[4] - trans[1] * trans[5];
	行列号
	double dRow = (trans[4] * (lon - trans[0]) - trans[1] * (lat - trans[3])) / dTemp;
	double dCol = (trans[2] * (lat - trans[3]) - trans[5] * (lon - trans[0])) / dTemp;
	int dx = (int)dCol;
	int dy = (int)dRow;

	// 获取数据类型
	GDALDataType dType = GDALGetRasterDataType(hBand);
	int dTypeSize = GDALGetDataTypeSizeBytes(dType);
	// 一般高程数据类型就是float,因此不再进行判断,如果为了严谨应该判断类型
	float* buffer = (float*)CPLMalloc(sizeof(float) * 1);
	if (GDALRasterIO(hBand, GF_Read, dx, dy, 1, 1, buffer, 1, 1, GDT_Float32, 0, 0) != CE_None)
	{
		return 0.0;
	}
	float dem = *buffer;
	CPLFree(buffer);
	GDALClose(hDS);
	return dem;
}

int main()
{
	const char* file_path_name = "E:/data/terrain/dem.tif";
	float lon = 89.7081101388;
	float lat = 30.9426533909;
	float alt = read_elevation(file_path_name, lon, lat);
	printf("经度:%.6f, 维度%.6f, 处的高程为:%.6f\n", lon,lat,alt);

	return 0;
}

你可能感兴趣的:(osg,gdal)