Gangmax Blog

GPS Shift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# From: https://github.com/scateu/PyWGS84ToGCJ02
# Issue description: https://en.wikipedia.org/wiki/Restrictions_on_geographic_data_in_China

from math import pi,sqrt,sin,cos

# a python binding of https://on4wp7.codeplex.com/SourceControl/changeset/view/21483#353936

# Krasovsky 1940
#
# a = 6378245.0, 1/f = 298.3
# b = a * (1 - f)
# ee = (a^2 - b^2) / a^2
a = 6378245.0
ee = 0.00669342162296594323

# Shift "World Geodetic System -> Mars Geodetic System".
def shift(wgLat, wgLon):
"""
transform(latitude,longitude) , WGS84
return (latitude,longitude) , GCJ02
"""
if (outOfChina(wgLat, wgLon)):
return wgLat, wgLon
dLat = transformLat(wgLon - 105.0, wgLat - 35.0)
dLon = transformLon(wgLon - 105.0, wgLat - 35.0)
radLat = wgLat / 180.0 * pi
magic = sin(radLat)
magic = 1 - ee * magic * magic
sqrtMagic = sqrt(magic)
dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * pi)
dLon = (dLon * 180.0) / (a / sqrtMagic * cos(radLat) * pi)
mgLat = wgLat + dLat
mgLon = wgLon + dLon
return mgLat, mgLon

def outOfChina(lat, lon):
if (lon < 72.004 or lon > 137.8347):
return True
if (lat < 0.8293 or lat > 55.8271):
return True
return False

def transformLat(x, y):
ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * sqrt(abs(x))
ret += (20.0 * sin(6.0 * x * pi) + 20.0 * sin(2.0 * x * pi)) * 2.0 / 3.0
ret += (20.0 * sin(y * pi) + 40.0 * sin(y / 3.0 * pi)) * 2.0 / 3.0
ret += (160.0 * sin(y / 12.0 * pi) + 320 * sin(y * pi / 30.0)) * 2.0 / 3.0
return ret

def transformLon(x, y):
ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * sqrt(abs(x))
ret += (20.0 * sin(6.0 * x * pi) + 20.0 * sin(2.0 * x * pi)) * 2.0 / 3.0
ret += (20.0 * sin(x * pi) + 40.0 * sin(x / 3.0 * pi)) * 2.0 / 3.0
ret += (150.0 * sin(x / 12.0 * pi) + 300 * sin(x / 30.0 * pi)) * 2.0 / 3.0
return ret

def unshift(mgLat, mgLon):
'''
Unshift "Mars Geodetic System -> World Geodetic System".
From: https://blog.csdn.net/coolypf/article/details/8686588
Shift the given mars coordinates again to get the delta amount, then
subtract the delta from the mars coordinates to get the original GPS
coordinates.
'''
lat2, lon2 = shift(mgLat, mgLon)
latDelta = lat2 - mgLat
lonDelta = lon2 - mgLon
return mgLat - latDelta, mgLon - lonDelta

def ton(degree, minute, second):
''' Convert "degree/minute/second" coordinate value to single numerial. '''
return degree + minute * 1.0 / 60 + second * 1.0 / 3600

lat, lon = shift(39.90768, 116.39101)
print('Shifted lat={}, lon={}'.format(lat, lon))
lat, lon = unshift(lat, lon)
print('Unhifted lat={}, lon={}'.format(lat, lon))

Comments