Location – Latitude/Longitude (Lat/Lon) to Degrees Minutes Seconds (DMS) Conversion – JavaScript

Location - Latitude Longitude (LatLon) to Degrees Minutes Seconds (DMS) Conversion - JavaScript

Location – Latitude/Longitude (Lat/Lon) to Degrees Minutes Seconds (DMS) Conversion – JavaScript

Sample JavaScript Program:

function truncate(n) {
    return n > 0 ? Math.floor(n) : Math.ceil(n);
}

let getDMS = function (dd, longOrLat) {
    let hemisphere = /^[WE]|(?:lon)/i.test(longOrLat)
    ? dd < 0
      ? "W"
      : "E"
    : dd < 0
      ? "S"
      : "N";
    
    const absDD = Math.abs(dd);
    const degrees = truncate(absDD);
    const minutes = truncate((absDD - degrees) * 60);
    const seconds = ((absDD - degrees - minutes / 60) * Math.pow(60, 2)).toFixed(2);
    
    let dmsArray = [degrees, minutes, seconds, hemisphere];
    return `${dmsArray[0]}°${dmsArray[1]}'${dmsArray[2]}" ${dmsArray[3]}`;
}

let lat = 13.041107;
let lon = 80.233232;

let latDMS = getDMS(lat, 'lat'); 
let lonDMS = getDMS(lon, 'long');
console.log('latDMS: '+ latDMS);
console.log('lonDMS: '+ lonDMS);

Result:

latDMS: 13°2'27.99" N
lonDMS: 80°13'59.64" E

[ YOU MAY ALSO LIKE ]

Leave a Reply