javascriptfunctionangle

Decimal Degrees to Degrees Minutes And Seconds in Javascript


Im trying to write a function that takes my decimal degrees (lat or long) and converts them to DMS degrees minutes seconds. I know I am meant to times the decimal point number by 60 then it's decimal again. But am a noob. Would I split the number?

function ConvertDDToDMS(DD) {
    eg. DD =-42.4
    D= 42;
    M= 4*60;
    S= .M * 60;
    var DMS =

    return DMS //append Direction (N, S, E, W);
}

Am I on the right track?


Solution

  • Update: I remove the part that did not make any sense (thanks cwolves!).

    Here you have yet another implementation. It won't be as short nor efficient as the previous ones, but hopefully much easier to understand.

    To get it right, first you need to understand how the calculations are done and only then attempt to implement them. For that, pseudocode is a great option, since you write down the steps in plain English or a simplified syntax that is easy to understand, and then translate it onto the programming language of choice.

    I hope it's useful!

    /* This is the pseudocode you need to follow:
     * It's a modified version from 
     * http://en.wikipedia.org/wiki/Geographic_coordinate_conversion#Conversion_from_Decimal_Degree_to_DMS
    
    function deg_to_dms ( degfloat )
       Compute degrees, minutes and seconds:
       deg ← integerpart ( degfloat )
       minfloat ← 60 * ( degfloat - deg )
       min ← integerpart ( minfloat )
       secfloat ← 60 * ( minfloat - min )
       Round seconds to desired accuracy:
       secfloat ← round( secfloat, digits )
       After rounding, the seconds might become 60. These two
       if-tests are not necessary if no rounding is done.
       if secfloat = 60
          min ← min + 1
          secfloat ← 0
       end if
       if min = 60
          deg ← deg + 1
          min ← 0
       end if
       Return output:
       return ( deg, min, secfloat )
    end function
    */
    
    function deg_to_dms (deg) {
       var d = Math.floor (deg);
       var minfloat = (deg-d)*60;
       var m = Math.floor(minfloat);
       var secfloat = (minfloat-m)*60;
       var s = Math.round(secfloat);
       // After rounding, the seconds might become 60. These two
       // if-tests are not necessary if no rounding is done.
       if (s==60) {
         m++;
         s=0;
       }
       if (m==60) {
         d++;
         m=0;
       }
       return ("" + d + ":" + m + ":" + s);
    }