Javascript 中的十进制度到度分和秒

发布于 2024-11-03 11:21:33 字数 291 浏览 1 评论 0原文

我正在尝试编写一个函数,获取我的十进制度数(纬度或经度)并将它们转换为 DMS 度分秒。我知道我应该将小数点乘以 60,然后再次得到小数。但我是一个菜鸟。我会分割号码吗?

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);
}

我走在正确的轨道上吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

还给你自由 2024-11-10 11:21:33
function ConvertDDToDMS(D, lng) {
  return {
    dir: D < 0 ? (lng ? "W" : "S") : lng ? "E" : "N",
    deg: 0 | (D < 0 ? (D = -D) : D),
    min: 0 | (((D += 1e-9) % 1) * 60),
    sec: (0 | (((D * 60) % 1) * 6000)) / 100,
  };
}

上面给出了一个对象{deg, min, sec, dir},其中sec被截断为两位数(例如3.14),dir是N之一code>、ESW 取决于您是否将 lng(经度)参数设置为 true。例如:

ConvertDDToDMS(-18.213, true) == {
   deg : 18,
   min : 12,
   sec : 46.79,
   dir : 'W'
}

或者如果您只想要基本字符串:

function ConvertDDToDMS(D){
  return [0|D, 'd ', 0|(D=(D<0?-D:D)+1e-4)%1*60, "' ", 0|D*60%1*60, '"'].join('');
}

ConvertDDToDMS(-18.213) == `-18d 12' 47"`

[编辑 2019 年 6 月] - 修复一个 8 年前的错误,该错误有时会导致结果因转换精确分钟时的浮点数学而偏离 1 分钟,例如 转换DDToDMS(4 + 20/60)

[编辑 2021 年 12 月]——哎呀。修复#2。返回原始代码,并将 1e-9 添加到 a) 将任何稍低的浮点错误提升到下一个最高数字的值中,并且 b) 小于 .01 秒,因此对输出没有影响。将 1e-4 添加到“字符串”版本,这是相同的修复,但也舍入秒(接近 1/2 秒)。

function ConvertDDToDMS(D, lng) {
  return {
    dir: D < 0 ? (lng ? "W" : "S") : lng ? "E" : "N",
    deg: 0 | (D < 0 ? (D = -D) : D),
    min: 0 | (((D += 1e-9) % 1) * 60),
    sec: (0 | (((D * 60) % 1) * 6000)) / 100,
  };
}

The above gives you an object {deg, min, sec, dir} with sec truncated to two digits (e.g. 3.14) and dir being one of N, E, S, W depending on whether you set the lng (longitude) parameter to true. e.g.:

ConvertDDToDMS(-18.213, true) == {
   deg : 18,
   min : 12,
   sec : 46.79,
   dir : 'W'
}

Or if you just want the basic string:

function ConvertDDToDMS(D){
  return [0|D, 'd ', 0|(D=(D<0?-D:D)+1e-4)%1*60, "' ", 0|D*60%1*60, '"'].join('');
}

ConvertDDToDMS(-18.213) == `-18d 12' 47"`

[edit June 2019] -- fixing an 8 year old bug that would sometimes cause the result to be 1 minute off due to floating point math when converting an exact minute, e.g. ConvertDDToDMS(4 + 20/60).

[edit Dec 2021] -- Whoops. Fix #2. Went back to the original code and added 1e-9 to the value which a) bumps any slightly low floating point errors to the next highest number and b) is less than .01 sec, so has no effect on the output. Added 1e-4 to the "string" version which is the same fix, but also rounds seconds (it's close to 1/2 sec).

春夜浅 2024-11-10 11:21:33

目前尚不清楚您如何需要输出。这是一个以字符串形式返回所有 3 个值的版本:

function ConvertDDToDMS(dd)
{
    var deg = dd | 0; // truncate dd to get degrees
    var frac = Math.abs(dd - deg); // get fractional part
    var min = (frac * 60) | 0; // multiply fraction by 60 and truncate
    var sec = frac * 3600 - min * 60;
    return deg + "d " + min + "' " + sec + "\"";
}

It's not clear how you need the output. Here's a version that returns all 3 values as a string:

function ConvertDDToDMS(dd)
{
    var deg = dd | 0; // truncate dd to get degrees
    var frac = Math.abs(dd - deg); // get fractional part
    var min = (frac * 60) | 0; // multiply fraction by 60 and truncate
    var sec = frac * 3600 - min * 60;
    return deg + "d " + min + "' " + sec + "\"";
}
少女七分熟 2024-11-10 11:21:33

更新:我删除了没有任何意义的部分(感谢cwolves!)。

这里还有另一个实现。它不会像以前那样简短或高效,但希望更容易理解。

为了做到正确,首先您需要了解计算是如何完成的,然后才尝试实现它们。为此,伪代码是一个很好的选择,因为您可以用简单的英语或易于理解的简化语法写下步骤,然后将其翻译成所选的编程语言。

我希望它有用!

/* 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);
}

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);
}
迷你仙 2024-11-10 11:21:33

这个在 TypeScript 中工作 %100:

    ConvertDDToDMS(deg: number, lng: boolean): string {

    var d = parseInt(deg.toString());
    var minfloat = Math.abs((deg - d) * 60);
    var m = Math.floor(minfloat);
    var secfloat = (minfloat - m) * 60;
    var s = Math.round((secfloat + Number.EPSILON) * 100) / 100
    d = Math.abs(d);

    if (s == 60) {
      m++;
      s = 0;
    }
    if (m == 60) {
      d++;
      m = 0;
    }

    let dms = {
      dir: deg < 0 ? lng ? 'W' : 'S' : lng ? 'E' : 'N',
      deg: d,
      min: m,
      sec: s
    };
    return `${dms.deg}\u00B0 ${dms.min}' ${dms.sec}" ${dms.dir}`
  }

This one works %100 in TypeScript:

    ConvertDDToDMS(deg: number, lng: boolean): string {

    var d = parseInt(deg.toString());
    var minfloat = Math.abs((deg - d) * 60);
    var m = Math.floor(minfloat);
    var secfloat = (minfloat - m) * 60;
    var s = Math.round((secfloat + Number.EPSILON) * 100) / 100
    d = Math.abs(d);

    if (s == 60) {
      m++;
      s = 0;
    }
    if (m == 60) {
      d++;
      m = 0;
    }

    let dms = {
      dir: deg < 0 ? lng ? 'W' : 'S' : lng ? 'E' : 'N',
      deg: d,
      min: m,
      sec: s
    };
    return `${dms.deg}\u00B0 ${dms.min}' ${dms.sec}" ${dms.dir}`
  }
独夜无伴 2024-11-10 11:21:33

尝试一下这个工作完美!

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

function getDMS(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]}`;
}

var lat = 13.041107;
var lon = 80.233232;

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

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

Try this working perfect!!!

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

function getDMS(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]}`;
}

var lat = 13.041107;
var lon = 80.233232;

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

Output:
latDMS: 13°2'27.99" N
lonDMS: 80°13'59.64" E 
清引 2024-11-10 11:21:33

一种解决方案,可以选择指定输出秒数的小数位,并纠正由于舍入秒和分钟而导致的任何边缘情况。

// @ input {deg}     Numeric; degrees number to convert
// @ input {dplaces} Decimal places to use for output seconds
//                   Default 0 places
// @ return {DMS} string degrees (°) minutes (') seconds (")
//
function degToDMS (deg, dplaces=0) {
  var d = Math.floor (deg);          // make degrees
  var m = Math.floor((deg-d)*60);    // make minutes
  var s = Math.round(((deg-d)*60-m)*60*Math.pow(10,dplaces))/Math.pow(10,dplaces); // Make sec rounded
  s == 60 && (m++, s=0 );            // if seconds rounds to 60 then increment minutes, reset seconds
  m == 60 && (d++, m=0 );            // if minutes rounds to 60 then increment degress, reset minutes
  return (d + "° " + m + "' " + s+'"');   // create output DMS string
}

// ----- tests ------
console.log(degToDMS(55.23456));         // 55° 14' 4"
console.log(degToDMS(55.23456   ,3));    // 55° 14' 4.416"
console.log(degToDMS(4 + 20/60  ,2));    // 4° 20' 0"
console.log(degToDMS(89.64789   ,2));    // 89° 38' 52.4"
console.log(degToDMS(-23.1234567,3));    // -24° 52' 35.556"

A solution with the option for specifying the decimal places in output seconds and correction of any edge cases due to rounding seconds and minutes.

// @ input {deg}     Numeric; degrees number to convert
// @ input {dplaces} Decimal places to use for output seconds
//                   Default 0 places
// @ return {DMS} string degrees (°) minutes (') seconds (")
//
function degToDMS (deg, dplaces=0) {
  var d = Math.floor (deg);          // make degrees
  var m = Math.floor((deg-d)*60);    // make minutes
  var s = Math.round(((deg-d)*60-m)*60*Math.pow(10,dplaces))/Math.pow(10,dplaces); // Make sec rounded
  s == 60 && (m++, s=0 );            // if seconds rounds to 60 then increment minutes, reset seconds
  m == 60 && (d++, m=0 );            // if minutes rounds to 60 then increment degress, reset minutes
  return (d + "° " + m + "' " + s+'"');   // create output DMS string
}

// ----- tests ------
console.log(degToDMS(55.23456));         // 55° 14' 4"
console.log(degToDMS(55.23456   ,3));    // 55° 14' 4.416"
console.log(degToDMS(4 + 20/60  ,2));    // 4° 20' 0"
console.log(degToDMS(89.64789   ,2));    // 89° 38' 52.4"
console.log(degToDMS(-23.1234567,3));    // -24° 52' 35.556"

囍孤女 2024-11-10 11:21:33
private static DecimalFormat DecimalFormat = new DecimalFormat(".##");
public static void main(String[] args){
    double decimal_degrees = 22.4229541515;

    System.out.println(getDMS(decimal_degrees));
}
public static String getDMS(double decimal_degrees) {
    double degree =  Math.floor(decimal_degrees);
    double minutes = ((decimal_degrees - Math.floor(decimal_degrees)) * 60.0); 
    double seconds = (minutes - Math.floor(minutes)) * 60.0;
    return ((int)degree)+":"+((int)minutes)+":"+decimalFormat.format(seconds);

}

输入:22.4229541515 输出:22:25:22.63

private static DecimalFormat DecimalFormat = new DecimalFormat(".##");
public static void main(String[] args){
    double decimal_degrees = 22.4229541515;

    System.out.println(getDMS(decimal_degrees));
}
public static String getDMS(double decimal_degrees) {
    double degree =  Math.floor(decimal_degrees);
    double minutes = ((decimal_degrees - Math.floor(decimal_degrees)) * 60.0); 
    double seconds = (minutes - Math.floor(minutes)) * 60.0;
    return ((int)degree)+":"+((int)minutes)+":"+decimalFormat.format(seconds);

}

INPUT : 22.4229541515 OUTPUT: 22:25:22.63

唔猫 2024-11-10 11:21:33

我很惊讶所有解决方案都使用一些额外的逻辑来处理“舍入到 60”的情况(如果他们完全意识到这一点),但没有人想到以相反的方式做这件事,从(四舍五入的)秒开始,然后使用 mod 和 int-div 而不必担心所有这些:

function coordToStr(coord)
{   
    let seconds = Math.round(Math.abs(coord) * 3600)
    let sec = Math.floor(seconds % 60)
    let minutes = Math.floor(seconds / 60)
    let min = minutes % 60
    let deg = Math.floor(minutes / 60)
    return deg + "°" + ((min < 10) ? "0" : "") + min + "'" + ((sec < 10) ? "0" : "") + sec
}

抱歉,这没有 N/S、E/W 部分,需要一些额外的方法来调用它。

如果你想要第二个分数,你可以使用这个:

function coordToStrWithDecimals(coord)
{   
    let centiSecs = Math.round(Math.abs(coord) * 360000)
    let frac = Math.floor(centiSecs % 100)
    let seconds = Math.floor(centiSecs / 100)
    let sec = Math.floor(seconds % 60)
    let minutes = Math.floor(seconds / 60)
    let min = minutes % 60
    let deg = Math.floor(minutes / 60)
    return deg + "°" + ((min < 10) ? "0" : "") + min + "'" + ((sec < 10) ? "0" : "") + sec + "." + ((frac < 10) ? "0" : "") + frac + '"'
}

I'm surprised all solutions are using some additional logic to handle the "rounds to 60" cases (if they're aware of it at all), but nobody thought of doing it the other way round, starting with (rounded) seconds and then using mod and int-div and not have to worry about all that:

function coordToStr(coord)
{   
    let seconds = Math.round(Math.abs(coord) * 3600)
    let sec = Math.floor(seconds % 60)
    let minutes = Math.floor(seconds / 60)
    let min = minutes % 60
    let deg = Math.floor(minutes / 60)
    return deg + "°" + ((min < 10) ? "0" : "") + min + "'" + ((sec < 10) ? "0" : "") + sec
}

Sorry, this is without the N/S, E/W part, would need some additional method calling it.

If you want second-fractions, you could use this:

function coordToStrWithDecimals(coord)
{   
    let centiSecs = Math.round(Math.abs(coord) * 360000)
    let frac = Math.floor(centiSecs % 100)
    let seconds = Math.floor(centiSecs / 100)
    let sec = Math.floor(seconds % 60)
    let minutes = Math.floor(seconds / 60)
    let min = minutes % 60
    let deg = Math.floor(minutes / 60)
    return deg + "°" + ((min < 10) ? "0" : "") + min + "'" + ((sec < 10) ? "0" : "") + sec + "." + ((frac < 10) ? "0" : "") + frac + '"'
}
治碍 2024-11-10 11:21:33

基于上面的答案,我已经将它们编写成 javascript 和 php 风格。

JS-

function convertDDToDMS(deg, lng){
    var d = parseInt(deg);
    var minfloat  = Math.abs((deg-d) * 60); 
    var m = Math.floor(minfloat);
    var secfloat = (minfloat-m)*60;
    var s = Math.round(secfloat); 
    d = Math.abs(d);

    if (s==60) {
        m++;
        s=0;
    }
    if (m==60) {
        d++;
        m=0;
    }

    return {
        dir : deg<0?lng?'W':'S':lng?'E':'N',
        deg : d,
        min : m,
        sec : s
    };
}

PHP-

function convertDDtoDMS($deg, $lng){
    $dd = intval($deg);
    $minfloat = abs(($deg - $dd) * 60);
    $mm = floor($minfloat);
    $secfloat = ($minfloat - $mm) * 60;
    $ss = round($secfloat);
    $dd = abs($dd);

    if($ss == 60){
        $mm++;
        $ss = 0;
    }

    if($mm == 60){
        $dd++;
        $mm = 0;
    }

    $dd = array(
        'dir' => $deg < 0 ? ($lng ? 'W' : 'S') : ($lng ? 'E' : 'N'),
        'deg' => abs($dd),
        'min' => $mm,
        'sec' => $ss,
    );

    return $dd;
}

Based on above answer, i've written them into javascript and php style.

JS-

function convertDDToDMS(deg, lng){
    var d = parseInt(deg);
    var minfloat  = Math.abs((deg-d) * 60); 
    var m = Math.floor(minfloat);
    var secfloat = (minfloat-m)*60;
    var s = Math.round(secfloat); 
    d = Math.abs(d);

    if (s==60) {
        m++;
        s=0;
    }
    if (m==60) {
        d++;
        m=0;
    }

    return {
        dir : deg<0?lng?'W':'S':lng?'E':'N',
        deg : d,
        min : m,
        sec : s
    };
}

PHP-

function convertDDtoDMS($deg, $lng){
    $dd = intval($deg);
    $minfloat = abs(($deg - $dd) * 60);
    $mm = floor($minfloat);
    $secfloat = ($minfloat - $mm) * 60;
    $ss = round($secfloat);
    $dd = abs($dd);

    if($ss == 60){
        $mm++;
        $ss = 0;
    }

    if($mm == 60){
        $dd++;
        $mm = 0;
    }

    $dd = array(
        'dir' => $deg < 0 ? ($lng ? 'W' : 'S') : ($lng ? 'E' : 'N'),
        'deg' => abs($dd),
        'min' => $mm,
        'sec' => $ss,
    );

    return $dd;
}
策马西风 2024-11-10 11:21:33

无法让上面的脚本工作,经过一段时间后想出了这个;
只需将 dms 提供给脚本

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;
}

,反之亦然,只需将度数提供给脚本,以及 lat(纬度)的 true 或 false

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;
}

希望这可以帮助人们。

couldnt get the script above working, after some time came up with 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..

極樂鬼 2024-11-10 11:21:33

这里的答案很好,但要以标准格式获取 DMS。

function padZero(num, targetLength) {
  return String(num).padStart(targetLength, "0");
}

function ddToDms(deg, latOrlon) {
  var absolute = Math.abs(deg);
  var degrees = Math.floor(absolute);
  var minNt = (absolute - degrees) * 60;
  var minutes = Math.floor(minNt);
  var seconds = ((minNt - minutes) * 60).toFixed(2);
  var secs = Math.floor(seconds);

  // Get cardinal direction
  if (latOrlon == "lat") {
    var direction = deg >= 0 ? "N" : "S";
  } else if (latOrlon == "lon") {
    var direction = deg >= 0 ? "E" : "W";
  }

  // Ensure 60 minutes add 1 to degree and 60 seconds add 1 to minutes
  if (seconds == 60) {
    minutes++;
    seconds = 0;
  }
  if (minutes == 60) {
    degrees++;
    minutes = 0;
  }

  // Pad with zero
  if (
    (degrees < 10 && latOrlon == "lat") ||
    (degrees > 10 && degrees < 100 && latOrlon == "lon")
  ) {
    var degrees = padZero(degrees, String(degrees).length + 1);
  } else if (degrees < 10 && latOrlon == "lon") {
    var degrees = padZero(degrees, String(degrees).length + 2);
  }
  if (minutes < 10) {
    var minutes = padZero(minutes, String(minutes).length + 1);
  }
  if (secs < 10) {
    var seconds = padZero(seconds, String(seconds).length + 1);
  }

  // Validate lat and lon
  if (deg > 90 && latOrlon == "lat") {
    alert("LATITUDE CANNOT BE MORE THAN 90");
  } else if (deg > 180 && latOrlon == "lon") {
    alert("LONGITUDE CANNOT BE MORE THAN 180");
  } else {
    return degrees + "°" + minutes + "'" + seconds + '"' + direction;
  }
}

// Example
var lat = 9.129438;
var lon = -4.233587;

var latDMS = ddToDms(lat, 'lat'); 
var lonDMS = ddToDms(lon, 'lon');

console.log('latDMS: '+ latDMS);
console.log('lonDMS: '+ lonDMS);

/*
Output
latDMS: 09°07'45.98"N
lonDMS: 004°14'00.91"W
*/

Good answers here but to get the DMS in the standard format.

function padZero(num, targetLength) {
  return String(num).padStart(targetLength, "0");
}

function ddToDms(deg, latOrlon) {
  var absolute = Math.abs(deg);
  var degrees = Math.floor(absolute);
  var minNt = (absolute - degrees) * 60;
  var minutes = Math.floor(minNt);
  var seconds = ((minNt - minutes) * 60).toFixed(2);
  var secs = Math.floor(seconds);

  // Get cardinal direction
  if (latOrlon == "lat") {
    var direction = deg >= 0 ? "N" : "S";
  } else if (latOrlon == "lon") {
    var direction = deg >= 0 ? "E" : "W";
  }

  // Ensure 60 minutes add 1 to degree and 60 seconds add 1 to minutes
  if (seconds == 60) {
    minutes++;
    seconds = 0;
  }
  if (minutes == 60) {
    degrees++;
    minutes = 0;
  }

  // Pad with zero
  if (
    (degrees < 10 && latOrlon == "lat") ||
    (degrees > 10 && degrees < 100 && latOrlon == "lon")
  ) {
    var degrees = padZero(degrees, String(degrees).length + 1);
  } else if (degrees < 10 && latOrlon == "lon") {
    var degrees = padZero(degrees, String(degrees).length + 2);
  }
  if (minutes < 10) {
    var minutes = padZero(minutes, String(minutes).length + 1);
  }
  if (secs < 10) {
    var seconds = padZero(seconds, String(seconds).length + 1);
  }

  // Validate lat and lon
  if (deg > 90 && latOrlon == "lat") {
    alert("LATITUDE CANNOT BE MORE THAN 90");
  } else if (deg > 180 && latOrlon == "lon") {
    alert("LONGITUDE CANNOT BE MORE THAN 180");
  } else {
    return degrees + "°" + minutes + "'" + seconds + '"' + direction;
  }
}

// Example
var lat = 9.129438;
var lon = -4.233587;

var latDMS = ddToDms(lat, 'lat'); 
var lonDMS = ddToDms(lon, 'lon');

console.log('latDMS: '+ latDMS);
console.log('lonDMS: '+ lonDMS);

/*
Output
latDMS: 09°07'45.98"N
lonDMS: 004°14'00.91"W
*/
谜兔 2024-11-10 11:21:33

仅供说明,答案

function ConvertDDToDMS(D){
return [0|D, 'd ', 0|(D<0?D=-D:D)%1*60, "' ", 0|D*60%1*60, '"'].join('');

}

对于 -1° 和 0° 之间的角度不起作用
厄运!
HC

just for remark, the answer

function ConvertDDToDMS(D){
return [0|D, 'd ', 0|(D<0?D=-D:D)%1*60, "' ", 0|D*60%1*60, '"'].join('');

}

does not work for angles between -1° and 0°.
Bad luck!
hc

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文