Skip to content

Instantly share code, notes, and snippets.

@sbeitzel
Created March 30, 2016 03:50
Show Gist options
  • Save sbeitzel/ae45387cea029d6027d82fe4d00e0239 to your computer and use it in GitHub Desktop.
Save sbeitzel/ae45387cea029d6027d82fe4d00e0239 to your computer and use it in GitHub Desktop.
JavaScript conversion of decimal degrees to degrees-minutes-seconds.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Decimal Degrees to Degrees-Minutes-Seconds</title>
<script>function convert()
{
var dd = document.getElementById("dd").value;
var sign="";
// TODO - degrees should be normalized to the range [0,365]
if( dd<0 ) { sign="-"; dd=-dd; }
// first, compute the total number of seconds: degrees * 60 minutes/degree * 60 seconds/minute
var totalSeconds = dd * 3600;
var degrees = Math.floor(dd);
totalSeconds -= degrees * 3600;
// totalSeconds now represents the fractional degrees
var minutes = Math.floor(totalSeconds / 60);
totalSeconds -= minutes * 60;
// totalSeconds now represents a number smaller than 60 -- the fractional part of the angle that is smaller than a minute of arc
var txt="d = int("+dd+"\u00B0) = "+degrees+"\u00B0";
txt+="\nm = int(("+dd+"\u00B0 - "+degrees+"\u00B0) \u00D7 60) = "+minutes+"'";
txt+="\ns = ("+dd+"\u00B0 - "+degrees+"\u00B0 - "+minutes+"'/60) \u00D7 3600 = "+totalSeconds+"\"";
txt+="\n\n"+sign+dd+"\u00B0";
txt+=" = "+sign+degrees+"\u00B0 "+minutes+"' "+totalSeconds+"\"";
document.getElementById("dms").innerHTML = txt;
}
</script>
</head>
<body>
<table>
<tr><th colspan="2">Decimal Degrees</th><th>Degrees, Minutes, Seconds</th></tr>
<tr><td rowspan="7"><input type="number" id="dd" name="dd" autofocus tabindex="1"></td>
<td><input type="button" onclick="convert()" value="Convert"></td>
<td rowspan="7"><textarea id="dms" name="dms" rows="7"></textarea></td></tr>
</table>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment