Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert GPS degree to decimal and vice-versa in jquery or javascript and PHP?

does someone know how to convert GPS degree to decimal values or vice versa?

I have to develop a way where users can insert an address and get the GPS values (both degree and/or decimal), but the main thing i need to know is how to convert the values, cause users can also insert GPS values (degree or decimal). Because i need to get the map from google maps this needs decimal.

I've tryed some codes but i get big numbers...like this one:

function ConvertDMSToDD(days, minutes, seconds, direction) {
    var dd = days + minutes/60 + seconds/(60*60);
    //alert(dd);
    if (direction == "S" || direction == "W") {
        dd = '-' + dd;
    } // Don't do anything for N or E
    return dd;
}

Any one?

Thank you.

like image 201
Pedro Soares Avatar asked Dec 30 '11 10:12

Pedro Soares


1 Answers

First thank you @Eugen Rieck for your help. Here is my final code, hope it can help someone:

degree to decimal

function getDMS2DD(days, minutes, seconds, direction) {
    direction.toUpperCase();
    var dd = days + minutes/60 + seconds/(60*60);
    //alert(dd);
    if (direction == "S" || direction == "W") {
        dd = dd*-1;
    } // Don't do anything for N or E
    return dd;
}

decimal to degree based on this link

function getDD2DMS(dms, type){

    var sign = 1, Abs=0;
    var days, minutes, secounds, direction;

    if(dms < 0)  { sign = -1; }
    Abs = Math.abs( Math.round(dms * 1000000.));
    //Math.round is used to eliminate the small error caused by rounding in the computer:
    //e.g. 0.2 is not the same as 0.20000000000284
    //Error checks
    if(type == "lat" && Abs > (90 * 1000000)){
        //alert(" Degrees Latitude must be in the range of -90. to 90. ");
        return false;
    } else if(type == "lon" && Abs > (180 * 1000000)){
        //alert(" Degrees Longitude must be in the range of -180 to 180. ");
        return false;
    }

    days = Math.floor(Abs / 1000000);
    minutes = Math.floor(((Abs/1000000) - days) * 60);
    secounds = ( Math.floor((( ((Abs/1000000) - days) * 60) - minutes) * 100000) *60/100000 ).toFixed();
    days = days * sign;
    if(type == 'lat') direction = days<0 ? 'S' : 'N';
    if(type == 'lon') direction = days<0 ? 'W' : 'E';
    //else return value     
    return (days * sign) + 'º ' + minutes + "' " + secounds + "'' " + direction;
}
alert(getDD2DMS(-8.68388888888889, 'lon'));

`

like image 160
Pedro Soares Avatar answered Nov 14 '22 23:11

Pedro Soares