Wednesday, February 15, 2017

Coordinate format conversion script

degrees minutes seconds or degrees decimal minutes  format to decimal degrees  format and vice versa.

import sys
import re

def conv(cl):
    h = float(cl[0])
    m = float(cl[1])
    s = float(cl[2])
    d = cl[3]
    mpl = 1
    if d.upper() == "S" or d.upper() == "W":
        mpl = -1
    nm = m + (s/60.0)
    nh = h + (nm/60.0)
    return nh * mpl

def convb(dec,dr):
    degsym =  '\xc2\xb0'
    minsym = "\xe2\x80\xb2"
    secsym =  "\xe2\x80\xb3"
   
    dec = float(dec)
    if dr == "lat":
        l = "N"
        if dec < 0:
            l = "S"
    elif dr == "lng":
        l = "E"
        if dec < 0:
            l = "W"
    afdecpnt = dec % 1
    rdec = dec - afdecpnt
    minu = afdecpnt * 60
    afdecpnt = minu % 1
    rmin = minu - afdecpnt
    sec = afdecpnt *60

    tr = str(rdec) + degsym +str(rmin) +minsym + str(sec) + secsym +l

    return tr



def cln(dstr):
    degsym =  '\xc2\xb0'
    minsym = "\xe2\x80\xb2"
    secsym =  "\xe2\x80\xb3"
    ltln = dstr
    ndstr = re.sub(degsym, " ", dstr)
    ndstr = re.sub(minsym, " ", ndstr)
    ndstr = re.sub(secsym, " ", ndstr)
    dstrl = ndstr.split()
    if re.search(minsym, ltln):
            pass
    else:
        m = 0
        dstrl.insert(1,m)
    if re.search(secsym, ltln):
        pass
    else:
        s = 0
        dstrl.insert(2,s)
    # ltln = re.sub(degsym|minsym|search, " ")
    return dstrl

ltln = sys.argv[1]

degsym =  '\xc2\xb0'
minsym = "\xe2\x80\xb2"
secsym =  "\xe2\x80\xb3"

if re.search(r"N|E|W|S", ltln.upper()):
    if re.search(degsym, ltln):
        ltlnl = ltln.split(",")
        # print ltlnl
        lt = cln(ltlnl[0].strip())
        ln = cln(ltlnl[1].strip())

        nlat = conv(lt)
        nlng = conv(ln)

    else:
        ltlnl = ltln.split(",")
        latl = ltlnl[0].strip().split()
        lngl = ltlnl[1].strip().split()
        nlat = conv(latl)
        nlng = conv(lngl)
else:
    lt,ln = ltln.split(",")
    nlat = convb(lt, "lat")
    nlng = convb(ln, "lng")


print str(nlat)+ "," + str(nlng)




****************************
valid input are
"33 33 33 N,22 22 22 E"
"33.0°33.0′33.00000012″N,22.0°22.0′22.00000008″E"
 33.5591666667,22.3727777778


example
$ python latlong.py 33.0°33.0′33.00000012″N,22.0°22.0′22.00000008″E
33.5591666667,22.3727777778



$  python latlong.py 33.5591666667,22.3727777778
33.0°33.0′33.00000012″N,22.0°22.0′22.00000008″E





No comments:

Post a Comment