?類文件
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 轉 GCJ02public 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})");