Converting latitude and longitude to decimal values in Python and JavaScript Python 20.09.2015

Geographic coordinates consist of latitude and longitude.

There are three basic forms of a coordinate.

  • Coordinate containing degrees (integer), minutes (integer), and seconds (integer, or real number) (DMS). For example, 36°57'9" N.
  • Coordinate containing degrees (integer) and minutes (real number) (MinDec).
  • Coordinate containing only degrees (real number) (DegDec). For example, 38.203655.

Python

# -*- coding: utf-8 -*-
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 (lat, lng)

dd = parse_dms("36°57'9' N 110°4'21' W")

print(dd)
print(dd2dms(dd[0]))

# (36.9525, -110.07249999999999)
# [36, 57, 9.000000000002046]

Also, you can use LatLon.

JavaScript

function ConvertDMSToDD(degrees, minutes, seconds, direction) {
    var dd = Number(degrees) + Number(minutes)/60 + Number(seconds)/(60*60);
    if (direction == "S" || direction == "W") { dd = dd * -1; }
    return dd;
}

function ParseDMS(input) {
    var parts = input.split(/[^\d\w]+/);
    var lat = ConvertDMSToDD(parts[0], parts[1], parts[2], parts[3]);
    var lng = ConvertDMSToDD(parts[4], parts[5], parts[6], parts[7]);
    return [lat, lng];
}

console.log(ParseDMS("36°57'9' N 110°4'21' W"))
[36.9525, -110.07249999999999]

Source