类文件
public static class WGS84ToGCJ02Helper
{
// 定义一些常量
private const double PI = 3.14159265358979324;
private const double A = 6378245.0;
private const double EE = 0.00669342162296594323;
// 判断坐标是否在中国范围内(不在国内则不进行转换)
private static bool OutOfChina(double lng, double lat)
{
return (lng < 72.004 || lng > 137.8347) ||
(lat < 0.8293 || lat > 55.8271);
}
// 转换纬度
private static double TransformLat(double x, double y)
{
double ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.Sqrt(Math.Abs(x));
ret += (20.0 * Math.Sin(6.0 * x * PI) + 20.0 * Math.Sin(2.0 * x * PI)) * 2.0 / 3.0;
ret += (20.0 * Math.Sin(y * PI) + 40.0 * Math.Sin(y / 3.0 * PI)) * 2.0 / 3.0;
ret += (160.0 * Math.Sin(y / 12.0 * PI) + 320 * Math.Sin(y * PI / 30.0)) * 2.0 / 3.0;
return ret;
}
// 转换经度
private static double TransformLng(double x, double y)
{
double ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.Sqrt(Math.Abs(x));
ret += (20.0 * Math.Sin(6.0 * x * PI) + 20.0 * Math.Sin(2.0 * x * PI)) * 2.0 / 3.0;
ret += (20.0 * Math.Sin(x * PI) + 40.0 * Math.Sin(x / 3.0 * PI)) * 2.0 / 3.0;
ret += (150.0 * Math.Sin(x / 12.0 * PI) + 300.0 * Math.Sin(x / 30.0 * PI)) * 2.0 / 3.0;
return ret;
}
// WGS84 转 GCJ02
public static (double lng, double lat) Wgs84ToGcj02(double wgsLng, double wgsLat)
{
if (OutOfChina(wgsLng, wgsLat))
{
return (wgsLng, wgsLat);
}
double dLat = TransformLat(wgsLng - 105.0, wgsLat - 35.0);
double dLng = TransformLng(wgsLng - 105.0, wgsLat - 35.0);
double radLat = wgsLat / 180.0 * PI;
double magic = Math.Sin(radLat);
magic = 1 - EE * magic * magic;
double sqrtMagic = Math.Sqrt(magic);
dLat = (dLat * 180.0) / ((A * (1 - EE)) / (magic * sqrtMagic) * PI);
dLng = (dLng * 180.0) / (A / sqrtMagic * Math.Cos(radLat) * PI);
double mgLat = wgsLat + dLat;
double mgLng = wgsLng + dLng;
return (mgLng, mgLat);
}
}
调用
// 示例:北京天安门的 WGS84 坐标
double wgsLng = 116.397228;
double wgsLat = 39.907501;
// 转换为 GCJ02 坐标
var gcjCoord = WGS84ToGCJ02Helper.Wgs84ToGcj02(wgsLng, wgsLat);
Console.WriteLine($"WGS84 坐标: ({wgsLng}, {wgsLat})");
Console.WriteLine($"GCJ02 坐标: ({gcjCoord.lng}, {gcjCoord.lat})");