How to convert lat long from decimal degrees to DMS format?
function toDegreesMinutesAndSeconds(coordinate) {
var absolute = Math.abs(coordinate);
var degrees = Math.floor(absolute);
var minutesNotTruncated = (absolute - degrees) * 60;
var minutes = Math.floor(minutesNotTruncated);
var seconds = Math.floor((minutesNotTruncated - minutes) * 60);
return degrees + " " + minutes + " " + seconds;
}
function convertDMS(lat, lng) {
var latitude = toDegreesMinutesAndSeconds(lat);
var latitudeCardinal = lat >= 0 ? "N" : "S";
var longitude = toDegreesMinutesAndSeconds(lng);
var longitudeCardinal = lng >= 0 ? "E" : "W";
return latitude + " " + latitudeCardinal + "\n" + longitude + " " + longitudeCardinal;
}
Here's an explanation on how this code works:
- The processing method for the latitude and longitude is pretty much the same, so I abstracted that out to the
toDegreesMinutesAndSeconds
function. That will return a string that will show, well, degrees, minutes, and seconds.- This function will start with the coordinate and truncate it. This value, in positive, is your amount of degrees.
- The decimal portion needs to be converted to minutes. We take what's left from that rounding and we multiply it by 60.
- We apply the same logic to get the seconds: so we use only the truncated number for our string but we keep the non-truncated to get the decimal part.
- Finally, we check if the original value of the coordinate was positive or negative. For latitude, positive (or zero) is North, otherwise South. For longitude, positive (or zero) is East, otherwise, West.
here's two simple functions i created for this; just give the dms to the script
function ConvertDMSToDEG(dms) {
var dms_Array = dms.split(/[^\d\w\.]+/);
var degrees = dms_Array[0];
var minutes = dms_Array[1];
var seconds = dms_Array[2];
var direction = dms_Array[3];
var deg = (Number(degrees) + Number(minutes)/60 + Number(seconds)/3600).toFixed(6);
if (direction == "S" || direction == "W") {
deg = deg * -1;
} // Don't do anything for N or E
return deg;
}
and visa versa just give the degrees to the script, and true of false for lat (latitude)
function ConvertDEGToDMS(deg, lat) {
var absolute = Math.abs(deg);
var degrees = Math.floor(absolute);
var minutesNotTruncated = (absolute - degrees) * 60;
var minutes = Math.floor(minutesNotTruncated);
var seconds = ((minutesNotTruncated - minutes) * 60).toFixed(2);
if (lat) {
var direction = deg >= 0 ? "N" : "S";
} else {
var direction = deg >= 0 ? "E" : "W";
}
return degrees + "°" + minutes + "'" + seconds + "\"" + direction;
}
hope this helps people..