Skip to content

Instantly share code, notes, and snippets.

@max-power
Forked from 140bytes/LICENSE.txt
Created July 20, 2012 19:19
Show Gist options
  • Save max-power/3152694 to your computer and use it in GitHub Desktop.
Save max-power/3152694 to your computer and use it in GitHub Desktop.
Geographic coordinate conversion Latitude/Longitude to Degrees, Minutes, Seconds
function(
a, // decimal value (ex. -14.23463)
b, // boundary; accepts "90" (Latitude) or "180" (Longitude)
c // precision for seconds
){
var
// get the direction indicator
H='NSEW'[
2*(b!=90) // expressions in brackets are booleans, that get coerced into 0 or 1
+(a<0) // is the decimal value less than 0, coerced into 0 or 1
],
a=(a<0?-a:a)%b, // convert value to absolute. shorten than Math.abs(a)
// also get the modulo of the value and the boundary
D=0|a, // Degress: get the integer value; like Math.floor(a)
a=(a-D)*60, // calulate the rest and multiply by 60
M=0|a, // Minutes
a=(a-M)*60,
S=a.toFixed(c); // Seconds
// return formatted values joined by non-breaking space
return [D+'°',M+'′',S+'″',H].join('\xA0')
}
function(a,b,c,d){d='NSEW'[2*(b>90)+(a<0)];a=a<0?-a:a;return~~a%b+'° '+(a*60%60|0)+'′ '+(a*3600%60).toFixed(c)+'″ '+d}
function(a,b,c,d){d='NSEW'.charAt(2*(b>90)+(a<0));a=a<0?-a:a;return~~a%b+'° '+(a*60%60|0)+'′ '+(a*3600%60).toFixed(c)+'″ '+d}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 YOUR_NAME_HERE <YOUR_URL_HERE>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "Geolocation to Degrees, Minutes, Seconds",
"description": "converts latitude or longitude decimal values to degrees, minutes, seconds",
"keywords": [
"latitude",
"longitude",
"dms",
"degrees",
"minutes",
"seconds",
"converter"
]
}
<!DOCTYPE html>
<title>Foo</title>
<div>Latitude: <code id="lat"></code></div>
<div>Longitude: <code id="lng"></code></div>
<script>
var dms = function(a,b,c,d){d='NSEW'[2*(b>90)+(a<0)];a=a<0?-a:a;return~~a%b+'° '+(a*60%60|0)+'′ '+(a*3600%60).toFixed(c)+'″ '+d}
navigator.geolocation.getCurrentPosition(function(position){
document.getElementById('lat').innerHTML = dms(position.coords.latitude, 90, 3)
document.getElementById('lng').innerHTML = dms(position.coords.longitude, 180, 3)
})
var v = 15.1245
console.log( v, dms( v, 90))
console.log(-v, dms(-v, 90))
console.log( v, dms( v, 180))
console.log(-v, dms(-v, 180))
</script>
@xpansive
Copy link

xpansive commented Aug 9, 2012

Saved one more byte by replacing a_60%60 with a%1_60.

function(a,b,c,d){d='NSEW'[2*(b>90)+(a<0)];a=a<0?-a:a;return~~a%b+'° '+(a%1*60|0)+'′ '+(a*3600%60).toFixed(c)+'″ '+d}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment