C++ 使用EPSG进行坐标转换

发布时间 2023-10-21 18:48:25作者: SpringBreath

场景

将WGS84坐标转换为CGCS2000坐标
使用epsg.io网站的坐标系转换功能可以检查转换结果是否正确
下面网址是示例代码
https://epsg.io/transform#s_srs=4326&t_srs=4538&x=88.0000000&y=47.0000000

转换示例代码

proj ver.9.2.0
安装proj库,使用vcpkg(vcpkg install proj:x64-windows)

#include <proj.h>

DPoint UEUtils::wgs84_to_cgcs2000(double lon, double lat)
{
	PJ_CONTEXT* ctx = proj_context_create();
	// 定义源和目标投影坐标系
	const char* src_crs = "+proj=longlat +datum=WGS84 +no_defs";
	const char* target_crs = "+proj=tmerc +lat_0=0 +lon_0=87 +k=1 +x_0=500000 +y_0=0 +ellps=GRS80 +units=m +no_defs";
	// 创建转换对象
	PJ* trans = proj_create_crs_to_crs(ctx, src_crs, target_crs, nullptr);
	if (!trans) { 
		std::cout << "无法创建坐标转换对象" << std::endl;
		proj_context_destroy(ctx);
		return DPoint(lon, lat);
	}
	PJ_COORD success = proj_trans(trans, PJ_FWD, proj_coord(lon, lat, 0, 0));
	
	DPoint result;
	result.x = success.xyzt.x;
	result.y = success.xyzt.y;

	proj_destroy(trans);
	proj_context_destroy(ctx);

	return result;
}

在代码中的src_crs 代表了投影字符串 WGS84(EPSG:4326),target_crs 代表了 投影字符串 CGCS2000 / 3-degree Gauss-Kruger CM 87E(EPSG:4538)

获取对应字符串的方式如下:

  1. 打开https://epsg.io/4538 , 其中的4538为EPSG代码
  2. 找到如下图字符串,PS(打开网页后请往下翻)
    image
  3. 将字符串末尾的 +type=crs去掉,结果为+proj=tmerc +lat_0=0 +lon_0=87 +k=1 +x_0=500000 +y_0=0 +ellps=GRS80 +units=m +no_defs

结束,有问题请在评论区留言(@_<)