Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert latitude longitude to decimal in python?

Tags:

python

Assuming I have the following:

latitude = "20-55-70.010N"
longitude = "32-11-50.000W"

What is the easiest way to convert to decimal form? Is there some library?

Would converting from this seconds form be simpler?

 "149520.220N"
 "431182.897W"
like image 514
Rolando Avatar asked Feb 14 '23 00:02

Rolando


2 Answers

To handle "N", "S", "W" and "E", one would tweak @wwii's solution:

def convert(tude):
    multiplier = 1 if tude[-1] in ['N', 'E'] else -1
    return multiplier * sum(float(x) / 60 ** n for n, x in enumerate(tude[:-1].split('-')))

then:

print('20-55-70.010N: ' + convert('20-55-70.010N'))
print('32-11-50.000W: ' + convert('32-11-50.000W'))

results in:

20-55-70.010N: 20.9361138889
32-11-50.000W: -32.1972222222
like image 172
Potrebic Avatar answered Mar 06 '23 03:03

Potrebic


This should do the trick

latitude = "20-55-70.010N"
longitude = "32-11-50.000W"

##assuming N latitude and W longitude
latitude = sum(float(x) / 60 ** n for n, x in enumerate(latitude[:-1].split('-')))  * (1 if 'N' in latitude[-1] else -1)
longitude = sum(float(x) / 60 ** n for n, x in enumerate(longitude[:-1].split('-'))) * (1 if 'E' in longitude[-1] else -1)

That's getting a bit long for my tastes, maybe keep it simple:

latitude = "20-55-70.010N"
N = 'N' in latitude
d, m, s = map(float, latitude[:-1].split('-'))
latitude = (d + m / 60. + s / 3600.) * (1 if N else -1)
longitude = "32-11-50.000W"
W = 'W' in longitude
d, m, s = map(float, longitude[:-1].split('-'))
longitude = (d + m / 60. + s / 3600.) * (-1 if W else 1)
like image 26
wwii Avatar answered Mar 06 '23 05:03

wwii