Friday, February 23, 2024
 Popular · Latest · Hot · Upcoming
29
rated 0 times [  30] [ 1]  / answers: 1 / hits: 18660  / 8 Years ago, sat, june 18, 2016, 12:00:00

Assuming I have a latitude longitude: 38.898556, -77.037852. How do I convert this to DMS?



Expected output is:



38 53 55 N
77 2 16 W


Want to be able to accept both a latitude and longitude as input parameters in the function.



Current function is as follows:



function convertDMS( lat, lng ) {

var convertLat = Math.abs(lat);
var LatDeg = Math.floor(convertLat);
var LatMin = (Math.floor((convertLat - LatDeg) * 60));
var LatCardinal = ((lat > 0) ? n : s);

var convertLng = Math.abs(lng);
var LngDeg = Math.floor(convertLng);
var LngMin = (Math.floor((convertLng - LngDeg) * 60));
var LngCardinal = ((lng > 0) ? e : w);

return LatDeg + LatCardinal + LatMin + + LngDeg + LngCardinal + LngMin;
}

More From » javascript

 Answers
95


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.


[#61726] Wednesday, June 15, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
keyonna

Total Points: 521
Total Questions: 104
Total Answers: 96

Location: Samoa
Member since Tue, May 3, 2022
2 Years ago
;