Utils.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /*
  2. 205.395583333332 = 205°23'44.1"
  3. 1,直接读取"度":205
  4. 2,(205.395583333332-205)*60=23.734999999920 得到"分":23
  5. 3,(23.734999999920-23)*60=44.099999995200 得到"秒":44.1
  6. return string,
  7. */
  8. function latLngDecimalToDegrees(decimal) {
  9. let absDecimal = Math.abs(decimal);
  10. let isNegative = Math.abs(decimal) != decimal;
  11. let d = Math.floor(absDecimal); //度
  12. let m = Math.floor((absDecimal - d) * 60); //分
  13. let s = Math.round((absDecimal - d) * 3600 % 60); //秒
  14. if (s == 60) {
  15. s = 0;
  16. m++;
  17. }
  18. if (m == 60) {
  19. m = 0;
  20. d++;
  21. }
  22. //d = ('000'+d).slice(-3); // left-pad with leading zeros
  23. const mm = ('00' + m).slice(-2); // left-pad with leading zeros
  24. const ss = ('00' + s).slice(-2);
  25. //if (s<10) s = '0' + s; // left-pad with leading zeros (note may include decimals)
  26. return (isNegative ? "-" : "") + d + '°' + mm + "′" + ss + '″';
  27. }
  28. /*
  29. Decimal Degrees = Degrees + minutes/60 + seconds/3600
  30. 例:57°55'56.6" =57+55/60+56.6/3600=57.9323888888888
  31. return Float or NaN
  32. */
  33. function latLngDegreesToDecimal(degreesStr) {
  34. let degreesArr = degreesStr.split("°");
  35. let degrees = parseInt(degreesArr[0]);
  36. let isNegative = Math.abs(degrees) != degrees;
  37. if (degreesArr.length == 1) {
  38. return degrees;
  39. }
  40. let minutesArr = degreesArr[1].split("′");
  41. let minutes = parseInt(minutesArr[0]);
  42. if (minutesArr.length == 1) {
  43. return parseFloat((isNegative ? "-" : "") + (Math.abs(degrees) + Math.abs(minutes) / 60));
  44. }
  45. let secondsStr = minutesArr[1];
  46. let secondsArr = secondsStr.split('″');
  47. let seconds = parseFloat(secondsArr[0]);
  48. return parseFloat((isNegative ? "-" : "") + (Math.abs(degrees) + Math.abs(minutes) / 60 + Math.abs(seconds) / 3600));
  49. }
  50. function isObject(arg) {
  51. return typeof arg === 'object' && arg !== null;
  52. }
  53. function isUndefined(arg) {
  54. return arg === void 0;
  55. }
  56. function isString(arg) {
  57. return typeof arg === 'string';
  58. }
  59. function hasLine(obj) {
  60. return (isObject(obj)
  61. && isSafeString(obj.lat)
  62. && isSafeString(obj.lng));
  63. }
  64. function isSafeString(arg) {
  65. if (isUndefined(arg)) {
  66. return false;
  67. }
  68. if (!isString(arg)) {
  69. return false;
  70. }
  71. if (arg.length == 0) {
  72. return false;
  73. }
  74. return true;
  75. }
  76. function hasPoint(obj) {
  77. return (isObject(obj)
  78. && isSafeString(obj.lat)
  79. && isSafeString(obj.lng));
  80. }
  81. module.exports = {
  82. latLngDecimalToDegrees,
  83. latLngDegreesToDecimal,
  84. isObject,
  85. isUndefined,
  86. isString,
  87. isSafeString,
  88. hasLine,
  89. hasPoint
  90. };