import math
import numbers
def longitude(value):
if not isinstance(value, numbers.Number):
return value
if value > 180 or value < -180:
return value
if value > 0:
side = 'E'
elif value < 0:
side = 'W'
else:
side = ''
return get_degree(value, side)
def latitude(value):
if not isinstance(value, numbers.Number):
return value
if value > 90 or value < -90:
return value
if value > 0:
side = 'N'
elif value < 0:
side = 'S'
else:
side = ''
return get_degree(value, side)
def get_degree(value, side):
result = u'{d}\u00b0 {m}\' {s}" {side}'
abs_value = math.fabs(value)
degrees = math.trunc(abs_value)
minutes = math.trunc((abs_value * 60) % 60)
seconds = round((abs_value * 3600) % 60, 4)
if seconds >= 60:
seconds = 0
minutes += 1
minutes = str(minutes).zfill(2)
seconds = str(seconds).zfill(2)
return result.format(side=side, d=degrees, m=minutes, s=seconds)
print(longitude(-108.502049)) #108° 30' 07" W
print(latitude(45.758718)) #45° 45' 31" N
反向运算
import re
def dms2dd(degrees, minutes, seconds, direction):
dd = float(degrees) + float(minutes)/60 + float(seconds)/(60*60);
if direction == 'S' or direction == 'W':
dd *= -1
return dd;
def dd2dms(deg):
d = int(deg)
md = abs(deg - d) * 60
m = int(md)
sd = (md - m) * 60
return [d, m, sd]
def parse_dms(dms):
parts = re.split('[^\d\w]+', dms)
lat = dms2dd(parts[0], parts[1], parts[2], parts[3])
lng = dms2dd(parts[4], parts[5], parts[6], parts[7])
return (round(lat,4), round(lng,4))
dd = parse_dms("45° 45' 31\" N 108° 30' 07\" W")
print(dd)
print(dd2dms(dd[0]))