import math
PI = 3.1415926535897932384626
AXIS = 6378245.0 # 长半轴
OFFSET = 0.00669342162296594323 # 偏心率平方
def transform_lat(x, y):
ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * math.sqrt(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
def transform_lng(x, y):
ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * math.sqrt(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
def gcj02_to_wgs84(lat, lng):
if out_of_china(lat, lng):
return lat, lng
dlat = transform_lat(lng - 105.0, lat - 35.0)
dlng = transform_lng(lng - 105.0, lat - 35.0)
radlat = lat / 180.0 * PI
magic = math.sin(radlat)
magic = 1 - OFFSET * magic * magic
sqrtmagic = math.sqrt(magic)
dlat = (dlat * 180.0) / ((AXIS * (1 - OFFSET)) / (magic * sqrtmagic) * PI)
dlng = (dlng * 180.0) / (AXIS / sqrtmagic * math.cos(radlat) * PI)
mglat = lat + dlat
mglng = lng + dlng
return lat * 2 - mglat, lng * 2 - mglng
def out_of_china(lat, lng):
return not (73.66 < lng < 135.05 and 3.86 < lat < 53.55)
gcj_lat, gcj_lng = 39.908823, 116.397470 # 这是北京天安门的GCJ-02坐标
wgs_lat, wgs_lng = gcj02_to_wgs84(gcj_lat, gcj_lng)
print(f"WGS-84坐标: 纬度 {wgs_lat}, 经度 {wgs_lng}")